An Essential Guide to Python Class Methods and When to ...

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

Python class methods aren't bound to any specific instance, but classes. · Use @classmethod decorator to change an instance method to a class method. Also, pass ... SkiptocontentHome»PythonOOP»PythonClassMethodsSummary:inthistutorial,you’lllearnaboutPythonclassmethodsandwhentousethemappropriately.IntroductiontoPythonclassmethodsSofar,youlearnedaboutinstancemethodsthatareboundtoaspecificinstanceofaclass.Instancemethodscanaccessinstancevariableswithinthesameclass.Toinvokeinstancemethods,youneedtocreateaninstanceoftheclassfirst.ThefollowingdefinesthePersonclass:classPerson: def__init__(self,first_name,last_name,age): self.first_name=first_name self.last_name=last_name self.age=age defget_full_name(self): returnf"{self.first_name}{self.last_name}" defintroduce(self): returnf"Hi.I'm{self.first_name}{self.last_name}.I'm{self.age}yearsold."Codelanguage:Python(python)ThePersonclasshasthreeinstancemethodsincluding__init__(),get_full_name(),andintroduce().SupposethatyouwanttoaddamethodthatcreatesananonymouspersontothePersonclass.Inordertodoso,youwouldcomeupwiththefollowingcode:classPerson: #...othermethods defcreate_anonymous(self): returnPerson('John','Doe',25) Codelanguage:Python(python)Thecreate_anonymous()isaninstancemethodthatreturnsananonymousperson.However,toinvokethecreate_anonymous()method,youneedtocreateaninstance,whichdoesn’tmakesenseinthiscase.ThisiswhyPythonclassmethodscomeintoplay.Aclassmethodisn’tboundtoanyspecificinstance.It’sboundtotheclassonly.Todefineaclassmethod:Firstplacethe@classmethoddecoratorabovethemethoddefinition.Fornow,youjustneedtounderstandthatthe@classmethoddecoratorwillchangeaninstancemethodtoaclassmethod.Second,renametheselfparametertocls.Theclsmeansclass.However,classisakeywordsoyoucannotuseitasaparameter.ThefollowingshowsthenewversionofthePersonclass:classPerson: def__init__(self,first_name,last_name,age): self.first_name=first_name self.last_name=last_name self.age=age defget_full_name(self): returnf"{self.first_name}{self.last_name}" defintroduce(self): returnf"Hi.I'm{self.first_name}{self.last_name}.I'm{self.age}yearsold." @classmethod defcreate_anonymous(cls): returnPerson('John','Doe',25) Codelanguage:Python(python)Thecreate_anonymous()methodcannotaccessinstanceattributes.Butitcanaccessclassattributesviatheclsvariable.CallingPythonclassmethodsTocallaclassmethod,youusetheclassname,followedbyadot,andthenthemethodnamelikethis:ClassName.method_name()Codelanguage:Python(python)Thefollowingexampleshowshowtocallthecreate_anonymous()classmethodofthePersonclass:anonymous=Person.create_anonymous() print(anonymous.introduce()) Codelanguage:Python(python)Output:Hi.I'mJohnDoe.I'm25yearsold.Codelanguage:Python(python)Classmethodsvs.instancemethodsThefollowingtableillustratesthedifferencesbetweenclassmethodsandinstancemethods:FeaturesclassmethodsInstancemethodsBindingClassAninstanceoftheclassCallingClass.method()object.method()AccessingClassattributesInstance&classattributesWhentousePythonclassmethodsYoucanuseclassmethodsforanymethodsthatarenotboundtoaspecificinstancebuttheclass.Inpractice,youoftenuseclassmethodsformethodsthatcreateaninstanceoftheclass.Whenamethodcreatesaninstanceoftheclassandreturnsit,themethodiscalledafactorymethod.Forexample,thecreate_anonymous()isafactorymethodbecauseitreturnsanewinstanceofthePersonclass.SummaryPythonclassmethodsaren’tboundtoanyspecificinstance,butclasses.Use@classmethoddecoratortochangeaninstancemethodtoaclassmethod.Also,passtheclsasthefirstparametertotheclassmethod.Useclassmethodsforfactorymethods.PreviouslyPythonInstanceVariablesUpNextPythonPrivateAttributesSearchfor:Classes&ObjectsSpecialMethodsPropertySingleInheritanceEnumerationsSOLIDPrinciplesMultipleInheritanceDescriptorsMetaProgrammingExceptions



請為這篇文章評分?