types — Dynamic type creation and names for built-in types ...
文章推薦指數: 80 %
Dynamic Type Creation¶ ... Creates a class object dynamically using the appropriate metaclass. The first three arguments are the components that make up a class ... Navigation index modules| next| previous| Python» 3.10.7Documentation» ThePythonStandardLibrary» DataTypes» types—Dynamictypecreationandnamesforbuilt-intypes | types—Dynamictypecreationandnamesforbuilt-intypes¶ Sourcecode:Lib/types.py Thismoduledefinesutilityfunctionstoassistindynamiccreationof newtypes. Italsodefinesnamesforsomeobjecttypesthatareusedbythestandard Pythoninterpreter,butnotexposedasbuiltinslikeintor strare. Finally,itprovidessomeadditionaltype-relatedutilityclassesandfunctions thatarenotfundamentalenoughtobebuiltins. DynamicTypeCreation¶ types.new_class(name,bases=(),kwds=None,exec_body=None)¶ Createsaclassobjectdynamicallyusingtheappropriatemetaclass. Thefirstthreeargumentsarethecomponentsthatmakeupaclass definitionheader:theclassname,thebaseclasses(inorder),the keywordarguments(suchasmetaclass). Theexec_bodyargumentisacallbackthatisusedtopopulatethe freshlycreatedclassnamespace.Itshouldaccepttheclassnamespace asitssoleargumentandupdatethenamespacedirectlywiththeclass contents.Ifnocallbackisprovided,ithasthesameeffectaspassing inlambdans:None. Newinversion3.3. types.prepare_class(name,bases=(),kwds=None)¶ Calculatestheappropriatemetaclassandcreatestheclassnamespace. Theargumentsarethecomponentsthatmakeupaclassdefinitionheader: theclassname,thebaseclasses(inorder)andthekeywordarguments (suchasmetaclass). Thereturnvalueisa3-tuple:metaclass,namespace,kwds metaclassistheappropriatemetaclass,namespaceisthe preparedclassnamespaceandkwdsisanupdatedcopyofthepassed inkwdsargumentwithany'metaclass'entryremoved.Ifnokwds argumentispassedin,thiswillbeanemptydict. Newinversion3.3. Changedinversion3.6:Thedefaultvalueforthenamespaceelementofthereturned tuplehaschanged.Nowaninsertion-order-preservingmappingis usedwhenthemetaclassdoesnothavea__prepare__method. Seealso MetaclassesFulldetailsoftheclasscreationprocesssupportedbythesefunctions PEP3115-MetaclassesinPython3000Introducedthe__prepare__namespacehook types.resolve_bases(bases)¶ ResolveMROentriesdynamicallyasspecifiedbyPEP560. Thisfunctionlooksforitemsinbasesthatarenotinstancesof type,andreturnsatuplewhereeachsuchobjectthathas an__mro_entries__methodisreplacedwithanunpackedresultof callingthismethod.Ifabasesitemisaninstanceoftype, oritdoesn’thavean__mro_entries__method,thenitisincludedin thereturntupleunchanged. Newinversion3.7. Seealso PEP560-Coresupportfortypingmoduleandgenerictypes StandardInterpreterTypes¶ Thismoduleprovidesnamesformanyofthetypesthatarerequiredto implementaPythoninterpreter.Itdeliberatelyavoidsincludingsomeof thetypesthatariseonlyincidentallyduringprocessingsuchasthe listiteratortype. Typicaluseofthesenamesisforisinstance()or issubclass()checks. Ifyouinstantiateanyofthesetypes,notethatsignaturesmayvarybetweenPythonversions. Standardnamesaredefinedforthefollowingtypes: types.NoneType¶ ThetypeofNone. Newinversion3.10. types.FunctionType¶ types.LambdaType¶ Thetypeofuser-definedfunctionsandfunctionscreatedby lambdaexpressions. Raisesanauditingeventfunction.__new__withargumentcode. Theauditeventonlyoccursfordirectinstantiationoffunctionobjects, andisnotraisedfornormalcompilation. types.GeneratorType¶ Thetypeofgenerator-iteratorobjects,createdby generatorfunctions. types.CoroutineType¶ Thetypeofcoroutineobjects,createdby asyncdeffunctions. Newinversion3.5. types.AsyncGeneratorType¶ Thetypeofasynchronousgenerator-iteratorobjects,createdby asynchronousgeneratorfunctions. Newinversion3.6. classtypes.CodeType(**kwargs)¶ Thetypeforcodeobjectssuchasreturnedbycompile(). Raisesanauditingeventcode.__new__withargumentscode,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags. Notethattheauditedargumentsmaynotmatchthenamesorpositions requiredbytheinitializer.Theauditeventonlyoccursfordirect instantiationofcodeobjects,andisnotraisedfornormalcompilation. replace(**kwargs)¶ Returnacopyofthecodeobjectwithnewvaluesforthespecifiedfields. Newinversion3.8. types.CellType¶ Thetypeforcellobjects:suchobjectsareusedascontainersfor afunction’sfreevariables. Newinversion3.8. types.MethodType¶ Thetypeofmethodsofuser-definedclassinstances. types.BuiltinFunctionType¶ types.BuiltinMethodType¶ Thetypeofbuilt-infunctionslikelen()orsys.exit(),and methodsofbuilt-inclasses.(Here,theterm“built-in”means“writtenin C”.) types.WrapperDescriptorType¶ Thetypeofmethodsofsomebuilt-indatatypesandbaseclassessuchas object.__init__()orobject.__lt__(). Newinversion3.7. types.MethodWrapperType¶ Thetypeofboundmethodsofsomebuilt-indatatypesandbaseclasses. Forexampleitisthetypeofobject().__str__. Newinversion3.7. types.NotImplementedType¶ ThetypeofNotImplemented. Newinversion3.10. types.MethodDescriptorType¶ Thetypeofmethodsofsomebuilt-indatatypessuchasstr.join(). Newinversion3.7. types.ClassMethodDescriptorType¶ Thetypeofunboundclassmethodsofsomebuilt-indatatypessuchas dict.__dict__['fromkeys']. Newinversion3.7. classtypes.ModuleType(name,doc=None)¶ Thetypeofmodules.Theconstructortakesthenameofthe moduletobecreatedandoptionallyitsdocstring. Note Useimportlib.util.module_from_spec()tocreateanewmoduleifyou wishtosetthevariousimport-controlledattributes. __doc__¶ Thedocstringofthemodule.DefaultstoNone. __loader__¶ Theloaderwhichloadedthemodule.DefaultstoNone. Thisattributeistomatchimportlib.machinery.ModuleSpec.loader asstoredintheattr:__spec__object. Note AfutureversionofPythonmaystopsettingthisattributebydefault. Toguardagainstthispotentialchange,preferablyreadfromthe __spec__attributeinsteadoruse getattr(module,"__loader__",None)ifyouexplicitlyneedtouse thisattribute. Changedinversion3.4:DefaultstoNone.Previouslytheattributewasoptional. __name__¶ Thenameofthemodule.Expectedtomatch importlib.machinery.ModuleSpec.name. __package__¶ Whichpackageamodulebelongsto.Ifthemoduleistop-level (i.e.notapartofanyspecificpackage)thentheattributeshouldbeset to'',elseitshouldbesettothenameofthepackage(whichcanbe __name__ifthemoduleisapackageitself).DefaultstoNone. Thisattributeistomatchimportlib.machinery.ModuleSpec.parent asstoredintheattr:__spec__object. Note AfutureversionofPythonmaystopsettingthisattributebydefault. Toguardagainstthispotentialchange,preferablyreadfromthe __spec__attributeinsteadoruse getattr(module,"__package__",None)ifyouexplicitlyneedtouse thisattribute. Changedinversion3.4:DefaultstoNone.Previouslytheattributewasoptional. __spec__¶ Arecordofthemodule’simport-system-relatedstate.Expectedtobean instanceofimportlib.machinery.ModuleSpec. Newinversion3.4. types.EllipsisType¶ ThetypeofEllipsis. Newinversion3.10. classtypes.GenericAlias(t_origin,t_args)¶ Thetypeofparameterizedgenericssuchas list[int]. t_originshouldbeanon-parameterizedgenericclass,suchaslist, tupleordict.t_argsshouldbeatuple(possiblyof length1)oftypeswhichparameterizet_origin: >>>fromtypesimportGenericAlias >>>list[int]==GenericAlias(list,(int,)) True >>>dict[str,int]==GenericAlias(dict,(str,int)) True Newinversion3.9. Changedinversion3.9.2:Thistypecannowbesubclassed. classtypes.UnionType¶ Thetypeofuniontypeexpressions. Newinversion3.10. classtypes.TracebackType(tb_next,tb_frame,tb_lasti,tb_lineno)¶ Thetypeoftracebackobjectssuchasfoundinsys.exc_info()[2]. Seethelanguagereferencefordetailsofthe availableattributesandoperations,andguidanceoncreatingtracebacks dynamically. types.FrameType¶ Thetypeofframeobjectssuchasfoundintb.tb_frameiftbisa tracebackobject. Seethelanguagereferencefordetailsofthe availableattributesandoperations. types.GetSetDescriptorType¶ ThetypeofobjectsdefinedinextensionmoduleswithPyGetSetDef,such asFrameType.f_localsorarray.array.typecode.Thistypeisusedas descriptorforobjectattributes;ithasthesamepurposeasthe propertytype,butforclassesdefinedinextensionmodules. types.MemberDescriptorType¶ ThetypeofobjectsdefinedinextensionmoduleswithPyMemberDef,such asdatetime.timedelta.days.ThistypeisusedasdescriptorforsimpleC datamemberswhichusestandardconversionfunctions;ithasthesamepurpose asthepropertytype,butforclassesdefinedinextensionmodules. CPythonimplementationdetail:InotherimplementationsofPython,thistypemaybeidenticalto GetSetDescriptorType. classtypes.MappingProxyType(mapping)¶ Read-onlyproxyofamapping.Itprovidesadynamicviewonthemapping’s entries,whichmeansthatwhenthemappingchanges,theviewreflectsthese changes. Newinversion3.3. Changedinversion3.9:Updatedtosupportthenewunion(|)operatorfromPEP584,which simplydelegatestotheunderlyingmapping. keyinproxy ReturnTrueiftheunderlyingmappinghasakeykey,else False. proxy[key] Returntheitemoftheunderlyingmappingwithkeykey.Raisesa KeyErrorifkeyisnotintheunderlyingmapping. iter(proxy) Returnaniteratoroverthekeysoftheunderlyingmapping.Thisisa shortcutforiter(proxy.keys()). len(proxy) Returnthenumberofitemsintheunderlyingmapping. copy()¶ Returnashallowcopyoftheunderlyingmapping. get(key[,default])¶ Returnthevalueforkeyifkeyisintheunderlyingmapping,else default.Ifdefaultisnotgiven,itdefaultstoNone,sothat thismethodneverraisesaKeyError. items()¶ Returnanewviewoftheunderlyingmapping’sitems((key,value) pairs). keys()¶ Returnanewviewoftheunderlyingmapping’skeys. values()¶ Returnanewviewoftheunderlyingmapping’svalues. reversed(proxy) Returnareverseiteratoroverthekeysoftheunderlyingmapping. Newinversion3.9. AdditionalUtilityClassesandFunctions¶ classtypes.SimpleNamespace¶ Asimpleobjectsubclassthatprovidesattributeaccesstoits namespace,aswellasameaningfulrepr. Unlikeobject,withSimpleNamespaceyoucanaddandremove attributes.IfaSimpleNamespaceobjectisinitializedwithkeyword arguments,thosearedirectlyaddedtotheunderlyingnamespace. Thetypeisroughlyequivalenttothefollowingcode: classSimpleNamespace: def__init__(self,/,**kwargs): self.__dict__.update(kwargs) def__repr__(self): items=(f"{k}={v!r}"fork,vinself.__dict__.items()) return"{}({})".format(type(self).__name__,",".join(items)) def__eq__(self,other): ifisinstance(self,SimpleNamespace)andisinstance(other,SimpleNamespace): returnself.__dict__==other.__dict__ returnNotImplemented SimpleNamespacemaybeusefulasareplacementforclassNS:pass. However,forastructuredrecordtypeusenamedtuple() instead. Newinversion3.3. Changedinversion3.9:Attributeorderinthereprchangedfromalphabeticaltoinsertion(like dict). types.DynamicClassAttribute(fget=None,fset=None,fdel=None,doc=None)¶ Routeattributeaccessonaclassto__getattr__. Thisisadescriptor,usedtodefineattributesthatactdifferentlywhen accessedthroughaninstanceandthroughaclass.Instanceaccessremains normal,butaccesstoanattributethroughaclasswillberoutedtothe class’s__getattr__method;thisisdonebyraisingAttributeError. Thisallowsonetohavepropertiesactiveonaninstance,andhavevirtual attributesontheclasswiththesamename(seeenum.Enumforanexample). Newinversion3.4. CoroutineUtilityFunctions¶ types.coroutine(gen_func)¶ Thisfunctiontransformsageneratorfunctionintoa coroutinefunctionwhichreturnsagenerator-basedcoroutine. Thegenerator-basedcoroutineisstillageneratoriterator, butisalsoconsideredtobeacoroutineobjectandis awaitable.However,itmaynotnecessarilyimplement the__await__()method. Ifgen_funcisageneratorfunction,itwillbemodifiedin-place. Ifgen_funcisnotageneratorfunction,itwillbewrapped.Ifit returnsaninstanceofcollections.abc.Generator,theinstance willbewrappedinanawaitableproxyobject.Allothertypes ofobjectswillbereturnedasis. Newinversion3.5. TableofContents types—Dynamictypecreationandnamesforbuilt-intypes DynamicTypeCreation StandardInterpreterTypes AdditionalUtilityClassesandFunctions CoroutineUtilityFunctions Previoustopic weakref—Weakreferences Nexttopic copy—Shallowanddeepcopyoperations ThisPage ReportaBug ShowSource Navigation index modules| next| previous| Python» 3.10.7Documentation» ThePythonStandardLibrary» DataTypes» types—Dynamictypecreationandnamesforbuilt-intypes |
延伸文章資訊
- 1types — Dynamic type creation and names for built-in types ...
Dynamic Type Creation¶ ... Creates a class object dynamically using the appropriate metaclass. Th...
- 2Introduction to classes and type in Python - Educative.io
If you look for type in the Python help console, you will see a description of the arguments that...
- 3Python type Class
In Python, a class is an instance of the type class. The type class creates other classs, therefo...
- 414. Dynamically Creating Classes with type - Python Course Eu
A user-defined class (or the class "object") is an instance of the class "type". So, we can see, ...
- 5type of class in python - Stack Overflow
New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class is ...