14. Dynamically Creating Classes with type - Python Course Eu

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

A user-defined class (or the class "object") is an instance of the class "type". So, we can see, that classes are created from type. In Python3 ... PythonTrainingCourses LivePythonclassesbyhighlyexperiencedinstructors: Instructor-ledtrainingcoursesbyBerndKlein InthisObjectOrientedProgrammingchapter IntrotoObjectOrientedProgramming ObjectOrientedProgramming Classvs.InstanceAttributes Propertiesvs.GettersandSetters ImplementingaCustomPropertyClass IntroductiontoDescriptors Inheritance MultipleInheritance MultipleInheritance:Example MagicMethods CallableInstancesofClasses InheritanceExample Slots:AvoidingDynamicallyCreatedAttributes PolynomialClass DynamicallyCreatingClasseswithtype RoadtoMetaclasses Metaclasses CountFunctioncallswiththehelpofaMetaclass The'ABC'ofAbstractBaseClasses ClassroomTrainingCourses ThiswebsitecontainsafreeandextensiveonlinetutorialbyBerndKlein,usingmaterialfromhisclassroomPythontrainingcourses. Ifyouareinterestedinaninstructor-ledclassroomtrainingcourse,havealookatthesePythonclasses: Instructor-ledtrainingcoursebyBerndKleinatBodenseo Image©kabliczech-Fotolia.com DeutscheAusgabe DEDynamischeErzeugungvonKlassen Pageauthor ThispagewaswrittenbyBerndKlein. BerndisanexperiencedcomputerscientistwithahistoryofworkingintheeducationmanagementindustryandisskilledinPython,Perl,ComputerScience,andC++.HehasaDipl.-Informatiker/MasterDegreefocusedinComputerSciencefromSaarlandUniversity. BerndKleinonFacebook BerndKleinonLinkedIn python-courseonFacebook PDFversion PDFversionofthissite HelpNeeded Thiswebsiteisfreeofannoyingads.Wewanttokeepitlikethis.Youcanhelpwithyourdonation: Theneedfordonations 14.DynamicallyCreatingClasseswithtype ByBerndKlein.Lastmodified:01Feb2022. Onthispage➤ Behindthescenes:RelationshipbetweenClassandtype Inthischapterofourtutorial,wewillprovideyouwithadeeperinsightintothemagichappeningbehindthescenes,whenwearedefiningaclassorcreatinganinstanceofaclass.Youmayaskyourself:"DoIreallyhavetolearnthesesadditionaldetailsonobjectorientedprogramminginPython?"Mostprobablynot,oryoubelongtothefewpeoplewhodesignclassesataveryadvancedlevel. First,wewillconcentrateontherelationshipbetweentypeandclass.Whiledefiningclassessofar,youmayhaveaskedyourself,whatishappening"behindthelines".Wehavealreadyseen,thatapplying"type"toanobjectreturnstheclassofwhichtheobjectisaninstanceof: x=[4,5,9] y="Hello" print(type(x),type(y)) OUTPUT: Ifyouapplytypeonthenameofaclassitself,yougettheclass"type"returned. print(type(list),type(str)) OUTPUT: Thisissimilartoapplyingtypeontype(x)andtype(y): x=[4,5,9] y="Hello" print(type(x),type(y)) print(type(type(x)),type(type(y))) OUTPUT: Auser-definedclass(ortheclass"object")isaninstanceoftheclass"type".So,wecansee,thatclassesarecreatedfromtype.InPython3thereisnodifferencebetween"classes"and"types".Theyareinmostcasesusedassynonyms. Thefactthatclassesareinstancesofaclass"type"allowsustoprogrammetaclasses.Wecancreateclasses,whichinheritfromtheclass"type".So,ametaclassisasubclassoftheclass"type". Insteadofonlyoneargument,typecanbecalledwiththreeparameters: type(classname,superclasses,attributes_dict) Iftypeiscalledwiththreearguments,itwillreturnanewtypeobject.Thisprovidesuswithadynamicformoftheclassstatement. "classname"isastringdefiningtheclassnameandbecomesthenameattribute; "superclasses"isalistortuplewiththesuperclassesofourclass.Thislistortuplewillbecomethebasesattribute; theattributes_dictisadictionary,functioningasthenamespaceofourclass.Itcontainsthedefinitionsfortheclassbodyanditbecomesthedictattribute. Let'shavealookatasimpleclassdefinition: classA: pass x=A() print(type(x)) OUTPUT: Wecanuse"type"forthepreviousclassdefintionaswell: A=type("A",(),{}) x=A() print(type(x)) OUTPUT: Generallyspeaking,thismeans,thatwecandefineaclassAwith type(classname,superclasses,attributedict) Whenwecall"type",thecallmethodoftypeiscalled.Thecallmethodrunstwoothermethods:newandinit: type.__new__(typeclass,classname,superclasses,attributedict) type.__init__(cls,classname,superclasses,attributedict) Thenewmethodcreatesandreturnsthenewclassobject,andafterthis,theinitmethodinitializesthenewlycreatedobject. classRobot: counter=0 def__init__(self,name): self.name=name defsayHello(self): return"Hi,Iam"+self.name defRob_init(self,name): self.name=name Robot2=type("Robot2", (), {"counter":0, "__init__":Rob_init, "sayHello":lambdaself:"Hi,Iam"+self.name}) x=Robot2("Marvin") print(x.name) print(x.sayHello()) y=Robot("Marvin") print(y.name) print(y.sayHello()) print(x.__dict__) print(y.__dict__) OUTPUT: Marvin Hi,IamMarvin Marvin Hi,IamMarvin {'name':'Marvin'} {'name':'Marvin'} TheclassdefinitionsforRobotandRobot2aresyntacticallycompletelydifferent,buttheyimplementlogicallythesameclass. WhatPythonactuallydoesinthefirstexample,i.e.the"usualway"ofdefiningclasses,isthefollowing:PythonprocessesthecompleteclassstatementfromclassRobottocollectthemethodsandattributesofRobottoaddthemtotheattributes_dictofthetypecall.So,PythonwillcalltypeinasimilarorthesamewayaswedidinRobot2. LivePythontraining Enjoyingthispage?WeofferlivePythontrainingcoursescoveringthecontentofthissite. See:LivePythoncoursesoverview UpcomingonlineCourses IntensiveAdvancedCourse 17Oct2022to21Oct2022 ObjectOrientedProgrammingwithPython 19Oct2022to21Oct2022 Enrolhere Onthispage



請為這篇文章評分?