Python type Class

文章推薦指數: 80 %
投票人數:10人

In Python, a class is an instance of the type class. The type class creates other classs, therefore, it is called a metaclass. Did you find this tutorial ... SkiptocontentHome»PythonOOP»PythontypeClassSummary:inthistutorial,you’lllearnaboutthePythontypeclassandunderstandhowPythonusesthetypeclasstocreateotherclasses.IntroductiontothePythontypeclassInPython,aclassisanobjectoftheclasstype.Forexample,thefollowingdefinesthePersonclasswithtwomethods__init__andgreeting:classPerson: def__init__(self,name,age): self.name=name self.age=age defgreeting(self): returnf'Hi,Iam{self.name}.Iam{self.age}yearold.'Codelanguage:Python(python)ThePersonclassisanobjectoftheclasstypeasshowninthefollowingstatement:print(type(Person))Codelanguage:Python(python)Output:Codelanguage:Python(python)ThePersonclassisaninstanceofthetypeclass:print(isinstance(Person,type))Codelanguage:Python(python)Pythonusesthetypeclasstocreateotherclasses.Thetypeclassitselfisacallable.Thefollowingshowsoneoftheconstructorsofthetypeclass:type(name,bases,dict)->anewtypeCodelanguage:Python(python)Theconstructorhasthreeparametersforcreatinganewclass:name:isthenameoftheclasse.g.,Personbasesisatuplethatcontainsthebaseclassesofthenewclass.Forexample,thePersoninheritsfromtheobjectclass,sothebasescontainsoneclass(object,)dictistheclassnamespaceTechnically,youcanusethetypeclasstocreateaclassdynamically.Beforedoingit,youneedtounderstandhowPythoncreatestheclasses.WhenthePythoninterpreterencountersaclassdefinitioninthecode,itwill:First,extracttheclassbodyasstring.Second,createaclassdictionaryfortheclassnamespace.Third,executetheclassbodytofilluptheclassdictionary.Finally,createanewinstanceoftypeusingtheabovetype()constructor.Let’semulatethestepsabovetocreateaPersonclassdynamically:First,extracttheclassbody:class_body=""" def__init__(self,name,age): self.name=name self.age=age defgreeting(self): returnf'Hi,Iam{self.name}.Iam{self.age}yearold.' """Codelanguage:Python(python)Second,createaclassdictionary:class_dict={}Codelanguage:Python(python)Third,executetheclassbodyandfilluptheclassdictionary:exec(class_body,globals(),class_dict)Codelanguage:Python(python)Theexec()functionexecutestheclassbodyandfillsuptheglobalandclassnamespaces.Finally,createanewPersonclassusingthetypeconstructor:Person=type('Person',(object,),class_dict)Codelanguage:Python(python)NotethatthePersonisaclass,whichisalsoanobject.ThePersonclassinheritsfromtheobjectclassandhasthenamespaceoftheclass_dict.ThefollowingshowsthetypeofthePersonclasswhichisthetypeclass:Codelanguage:Python(python)Anditisaninstanceofthetypeclass:print(isinstance(Person,type))Codelanguage:Python(python)Output:TrueCodelanguage:Python(python)Theclass_dicthasthetwofunctions__init__andgreeting:{'__init__':, 'greeting':}Codelanguage:Python(python)ThePerson.__dict__alsocontainsthesefunctions:mappingproxy({'__dict__':, '__doc__':None, '__init__':, '__module__':'__main__', '__weakref__':, 'greeting':})Codelanguage:Python(python)Inthisexample,Pythoncreatesthetypeclassdynamically,whichisthesameastheonethatyoudefinestaticallyinthecode.Becausethetypeclasscreatesotherclasses,weoftenrefertoitasametaclass.Ametaclassisaclassusedtocreateotherclasses.SummaryInPython,aclassisaninstanceofthetypeclass.Thetypeclasscreatesotherclasss,therefore,itiscalledametaclass.PreviouslyPython__new__UpNextPythonMetaclassSearchfor:Classes&ObjectsSpecialMethodsPropertySingleInheritanceEnumerationsSOLIDPrinciplesMultipleInheritanceDescriptorsMetaProgrammingExceptions



請為這篇文章評分?