classmethod() in Python - GeeksforGeeks

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

A class method takes cls as the first parameter while a static method needs no specific parameters. · A class method can access or modify the ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesclassmethod()inPythonClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeclassmethod()inPythonClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeclassmethod()inPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 13Sep,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Theclassmethod()isaninbuiltfunctioninPython,whichreturnsaclassmethodforagivenfunction.;Syntax:classmethod(function)Parameter:Thisfunctionacceptsthefunctionnameasaparameter.ReturnType:Thisfunctionreturnstheconvertedclassmethod.Youcanalsouse@classmethoddecoratorforclassmethoddefinition.Syntax: @classmethod deffun(cls,arg1,arg2,...):Where, fun:thefunctionthatneedstobeconvertedintoaclassmethodreturns:aclassmethodforfunction.classmethod()methodsareboundtoaclassratherthananobject.Classmethodscanbecalledbybothclassandobject.Thesemethodscanbecalledwithaclassorwithanobject. ClassmethodvsStaticMethodAclassmethodtakesclsasthefirstparameterwhileastaticmethodneedsnospecificparameters.Aclassmethodcanaccessormodifytheclassstatewhileastaticmethodcan’taccessormodifyit.Ingeneral,staticmethodsknownothingabouttheclassstate.Theyareutility-typemethodsthattakesomeparametersandworkuponthoseparameters.Ontheotherhandclassmethodsmusthaveclassasaparameter.Weuse@classmethoddecoratorinpythontocreateaclassmethodandweuse@staticmethoddecoratortocreateastaticmethodinpython.ExampleofclassmethodinPythonExample1:CreateasimpleclassmethodInthisexample,wearegoingtoseeahowtocreateclassmethod,forthiswecreatedaclasswithgeeksnamewithmembervariablecourseandcreatedafunctionpurchasewhichprintstheobject.Nowwepassedthemethodgeeks.purchaseintoclassmethodwhichconvertsthemethodstoaclassmethodandthenwecalltheclassfunctionpurchasewithoutcreatingafunctionobject.Python3classgeeks:    course='DSA'      defpurchase(obj):        print("Puchasecourse:",obj.course)    geeks.purchase=classmethod(geeks.purchase)geeks.purchase()Output:Puchasecourse:DSAExample2:Createclassmethodusingclassmethod()Python3#Pythonprogramtounderstandtheclassmethod  classStudent:      #createavariable    name="Geeksforgeeks"      #createafunction    defprint_name(obj):        print("Thenameis:",obj.name)    #createprint_nameclassmethod#beforecreatingthislineprint_name()#ItcanbecalledonlywithobjectnotwithclassStudent.print_name=classmethod(Student.print_name)  #nowthismethodcanbecalledasclassmethod#print_name()methodiscalledaclassmethodStudent.print_name()Output:Thenameis:GeeksforgeeksExample3:FactorymethodusingClassmethodUsesofclassmethod()functionareusedinfactorydesignpatternswherewewanttocallmanyfunctionswiththeclassnameratherthananobject.Python3#Pythonprogramtodemonstrate#useofaclassmethodandstaticmethod.fromdatetimeimportdate  classPerson:    def__init__(self,name,age):        self.name=name        self.age=age      #aclassmethodtocreatea    #Personobjectbybirthyear.    @classmethod    deffromBirthYear(cls,name,year):        returncls(name,date.today().year-year)      defdisplay(self):        print("Name:",self.name,"Age:",self.age)  person=Person('mayank',21)person.display()Output:Name:mayankAge:21The@classmethodDecoratorThe@classmethoddecoratorisabuilt-infunctiondecoratorwhichisanexpressionthatgetsevaluatedafteryourfunctionisdefined.Theresultofthatevaluationshadowsyourfunctiondefinition. Aclassmethodreceivestheclassastheimplicitfirstargument,justlikeaninstancemethodreceivestheinstance.Syntax:classC(object): @classmethod deffun(cls,arg1,arg2,...): ....Where,fun:thefunctionthatneedstobeconvertedintoaclassmethodreturns:aclassmethodforfunction.Note:Aclassmethodisamethodwhichisboundtotheclassandnottheobjectoftheclass.Theyhavetheaccesstothestateoftheclassasittakesaclassparameterthatpointstotheclassandnottheobjectinstance.Itcanmodifyaclassstatethatwouldapplyacrossalltheinstancesoftheclass.Forexample,itcanmodifyaclassvariablethatwouldbeapplicabletoalltheinstances.Inthebelowexampleweuseastaticmethod()andclassmethod()tocheckifapersonisanadultornot.Python#Pythonprogramtodemonstrate#useofaclassmethodandstaticmethod.fromdatetimeimportdate  classPerson:    def__init__(self,name,age):        self.name=name        self.age=age      #aclassmethodtocreatea    #Personobjectbybirthyear.    @classmethod    deffromBirthYear(cls,name,year):        returncls(name,date.today().year-year)      #astaticmethodtocheckifa    #Personisadultornot.    @staticmethod    defisAdult(age):        returnage>18  person1=Person('mayank',21)person2=Person.fromBirthYear('mayank',1996)  print(person1.age)print(person2.age)  #printtheresultprint(Person.isAdult(22))Output:21 25 TrueMyPersonalNotes arrow_drop_upSave LikeNext ClassmethodvsStaticmethodinPythonRecommendedArticlesPage:25,Feb1631,Jul1906,Jun1911,Jun1911,Jun1912,Jun1917,Aug1902,Sep1926,Sep1904,Mar2021,Apr2026,Apr2028,May2031,Jul2013,Aug2015,Aug2002,Jan2116,Dec2116,Dec2109,Feb1603,Jan2128,Oct2124,Jul1804,Aug16ArticleContributedBy:ankit15697@ankit15697VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:yegoun98kumar_satyamArticleTags:Python-FunctionsPythonPracticeTags:pythonpython-functionsReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?