Python classmethod() - Programiz

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

A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod. The ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLL PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear ExplorePythonExamples ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython AllPythonTutorials ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall Python JavaScript C C++ Java Kotlin LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples Built-inFunctions Pythonabs() Pythonany() Pythonall() Pythonascii() Pythonbin() Pythonbool() Pythonbytearray() Pythoncallable() Pythonbytes() Pythonchr() Pythoncompile() Pythonclassmethod() Pythoncomplex() Pythondelattr() Pythondict() Pythondir() Pythondivmod() Pythonenumerate() Pythonstaticmethod() Pythonfilter() Pythoneval() Pythonfloat() Pythonformat() Pythonfrozenset() Pythongetattr() Pythonglobals() Pythonexec() Pythonhasattr() Pythonhelp() Pythonhex() Pythonhash() Pythoninput() Pythonid() Pythonisinstance() Pythonint() Pythonissubclass() Pythoniter() Pythonlist()Function Pythonlocals() Pythonlen() Pythonmax() Pythonmin() Pythonmap() Pythonnext() Pythonmemoryview() Pythonobject() Pythonoct() Pythonord() Pythonopen() Pythonpow() Pythonprint() Pythonproperty() Pythonrange() Pythonrepr() Pythonreversed() Pythonround() Pythonset() Pythonsetattr() Pythonslice() Pythonsorted() Pythonstr() Pythonsum() Pythontuple()Function Pythontype() Pythonvars() Pythonzip() Python__import__() Pythonsuper() RelatedTopics Pythonsetattr() Pythonstaticmethod() Pythongetattr() Pythontimestamptodatetimeandvice-versa Pythonproperty() Pythondatetime Pythonclassmethod() Inthistutorial,wewilllearnaboutthePythonclassmethod()functionwiththehelpofexamples. Theclassmethod()methodreturnsaclassmethodforthegivenfunction. Example classStudent: marks=0 defcompute_marks(self,obtained_marks): marks=obtained_marks print('ObtainedMarks:',marks) #convertcompute_marks()toclassmethod Student.print_marks=classmethod(Student.compute_marks) Student.print_marks(88) #Output:ObtainedMarks:88 classmethod()Syntax Thesyntaxofclassmethod()methodis: classmethod(function) classmethod()isconsideredun-PythonicsoinnewerPythonversions,youcanusethe@classmethoddecoratorforclassmethoddefinition. Thesyntaxis: @classmethod deffunc(cls,args...) classmethod()Parameters classmethod()methodtakesasingleparameter: function-Functionthatneedstobeconvertedintoaclassmethod classmethod()ReturnValue classmethod()methodreturnsaclassmethodforthegivenfunction. Whatisaclassmethod? Aclassmethodisamethodthatisboundtoaclassratherthanitsobject.Itdoesn'trequirecreationofaclassinstance,muchlikestaticmethod. Thedifferencebetweenastaticmethodandaclassmethodis: Staticmethodknowsnothingabouttheclassandjustdealswiththeparameters Classmethodworkswiththeclasssinceitsparameterisalwaystheclassitself. Theclassmethodcanbecalledbothbytheclassanditsobject. Class.classmethod() Oreven Class().classmethod() Butnomatterwhat,theclassmethodisalwaysattachedtoaclasswiththefirstargumentastheclassitselfcls. defclassMethod(cls,args...) Example1:Createclassmethodusingclassmethod() classPerson: age=25 defprintAge(cls): print('Theageis:',cls.age) #createprintAgeclassmethod Person.printAge=classmethod(Person.printAge) Person.printAge() Output Theageis:25 Here,wehaveaclassPerson,withamembervariableageassignedto25. WealsohaveafunctionprintAgethattakesasingleparameterclsandnotselfweusuallytake. clsacceptstheclassPersonasaparameterratherthanPerson'sobject/instance. Now,wepassthemethodPerson.printAgeasanargumenttothefunctionclassmethod.Thisconvertsthemethodtoaclassmethodsothatitacceptsthefirstparameterasaclass(i.e.Person). Inthefinalline,wecallprintAgewithoutcreatingaPersonobjectlikewedoforstaticmethods.Thisprintstheclassvariableage. Whendoyouusetheclassmethod? 1.Factorymethods Factorymethodsarethosemethodsthatreturnaclassobject(likeconstructor)fordifferentusecases. ItissimilartofunctionoverloadinginC++.Since,Pythondoesn'thaveanythingassuch,classmethodsandstaticmethodsareused. Example2:Createfactorymethodusingclassmethod fromdatetimeimportdate #randomPerson classPerson: def__init__(self,name,age): self.name=name self.age=age @classmethod deffromBirthYear(cls,name,birthYear): returncls(name,date.today().year-birthYear) defdisplay(self): print(self.name+"'sageis:"+str(self.age)) person=Person('Adam',19) person.display() person1=Person.fromBirthYear('John',1985) person1.display() Output Adam'sageis:19 John'sageis:31 Here,wehavetwoclassinstancecreator,aconstructorandafromBirthYearmethod. Theconstructortakesnormalparametersnameandage.While,fromBirthYeartakesclass,nameandbirthYear,calculatesthecurrentagebysubtractingitwiththecurrentyearandreturnstheclassinstance. ThefromBirthYearmethodtakesPersonclass(notPersonobject)asthefirstparameterclsandreturnstheconstructorbycallingcls(name,date.today().year-birthYear),whichisequivalenttoPerson(name,date.today().year-birthYear) Beforethemethod,wesee@classmethod.ThisiscalledadecoratorforconvertingfromBirthYeartoaclassmethodasclassmethod(). 2.Correctinstancecreationininheritance Wheneveryouderiveaclassfromimplementingafactorymethodasaclassmethod,itensurescorrectinstancecreationofthederivedclass. Youcancreateastaticmethodfortheaboveexamplebuttheobjectitcreates,willalwaysbehardcodedasBaseclass. But,whenyouuseaclassmethod,itcreatesthecorrectinstanceofthederivedclass. Example3:Howtheclassmethodworksfortheinheritance? fromdatetimeimportdate #randomPerson classPerson: def__init__(self,name,age): self.name=name self.age=age @staticmethod deffromFathersAge(name,fatherAge,fatherPersonAgeDiff): returnPerson(name,date.today().year-fatherAge+fatherPersonAgeDiff) @classmethod deffromBirthYear(cls,name,birthYear): returncls(name,date.today().year-birthYear) defdisplay(self): print(self.name+"'sageis:"+str(self.age)) classMan(Person): sex='Male' man=Man.fromBirthYear('John',1985) print(isinstance(man,Man)) man1=Man.fromFathersAge('John',1965,20) print(isinstance(man1,Man)) Output True False Here,usingastaticmethodtocreateaclassinstancewantsustohardcodetheinstancetypeduringcreation. ThisclearlycausesaproblemwheninheritingPersontoMan. fromFathersAgemethoddoesn'treturnaManobjectbutitsbaseclassPerson'sobject. ThisviolatestheOOPparadigm.UsingaclassmethodasfromBirthYearcanensuretheOOP-nessofthecodesinceittakesthefirstparameterastheclassitselfandcallsitsfactorymethod. PreviousTutorial: Pythoncompile() NextTutorial: Pythoncomplex() Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank PythonReferencesPythonLibraryPythonstaticmethod()PythonLibraryPythonsetattr()PythonLibraryPythongetattr()PythonLibraryPythonproperty() TryPROforFREE LearnPythonInteractively



請為這篇文章評分?