Python super() - GeeksforGeeks

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

Python has a reserved method called “__init__.” In Object-Oriented Programming, it is referred to as a constructor. When this method is called ... 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 ▲RelatedArticlesPythonsuper()Python|super()insingleinheritanceClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframePythonsuper()Python|super()insingleinheritanceClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframePythonsuper()ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 12Sep,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle HowInheritanceisworkingwithoutsuperPython3#codeclassPerson:     #Constructor    def__init__(self,name,id):        self.name=name        self.id=id     #Tocheckifthispersonisanemployee    defDisplay(self):        print(self.name,self.id)      classEmp(Person):         def__init__(self,name,id):        self.name_=name     defPrint(self):        print("Empclasscalled") Emp_details=Emp("Mayank",103) #callingparentclassfunctionEmp_details.name_,Emp_details.nameOutput:--------------------------------------------------------------------------- AttributeErrorTraceback(mostrecentcalllast) in 24 25#callingparentclassfunction --->26Emp_details.name_,Emp_details.name AttributeError:'Emp'objecthasnoattribute'name'InabovecodeEmpclassisinheritsthePersonclassBothclasshasthe__init__constructortryingtocallname&name_fromotherclass ButwewillencountertheaboveerrorWithsuperimplementationininherentwecansolvetheproblem.examplecanfoundbelowThePythonsuper()functionreturnsobjectsrepresentedintheparent’sclassandisveryusefulin multipleandmultilevelinheritancestofindwhichclassthechildclassisextendingfirst.Syntaxofsuper()inPythonSyntax:super()Return:Returnaproxyobjectwhichrepresentstheparent’sclass.Exampleofsuper()functioninPythonPython3classEmp():    def__init__(self,id,name,Add):        self.id=id        self.name=name        self.Add=Add #ClassfreelancerinheritsEMPclassFreelance(Emp):    def__init__(self,id,name,Add,Emails):        super().__init__(id,name,Add)        self.Emails=Emails Emp_1=Freelance(103,"Surajkrgupta","Noida","KKK@gmails")print('TheIDis:',Emp_1.id)print('TheNameis:',Emp_1.name)print('TheAddressis:',Emp_1.Add)print('TheEmailsis:',Emp_1.Emails)Output:TheIDis:103 TheNameis:Surajkrgupta TheAddressis:Noida TheEmailsis:KKK@gmailsSolvingthefirstproblemusingsuperPython3#code#APythonprogramtodemonstrateinheritance classPerson:     #Constructor    def__init__(self,name,id):        self.name=name        self.id=id     #Tocheckifthispersonisanemployee    defDisplay(self):        print(self.name,self.id)      classEmp(Person):         def__init__(self,name,id):        self.name_=name        super().__init__(name,id)     defPrint(self):        print("Empclasscalled") Emp_details=Emp("Mayank",103) #callingparentclassfunctionprint(Emp_details.name_,Emp_details.name)outputMayankMayankUnderstandingPythonsuper()with__init__()methodsPythonhasareservedmethodcalled“__init__.”InObject-OrientedProgramming,itisreferredtoasaconstructor. Whenthismethodiscalleditallowstheclasstoinitializetheattributesoftheclass.Inaninheritedsubclass,aparentclasscanbereferredwiththeuseofthesuper()function.Thesuperfunctionreturnsatemporaryobjectofthesuperclassthatallowsaccesstoallofitsmethodstoitschildclass.Note:Formoreinformation,refertoInheritanceinPythonThebenefitsofusingasuper()functionare:Neednotrememberorspecifytheparentclassnametoaccessitsmethods.Thisfunctioncanbeusedbothinsingleandmultipleinheritances.Thisimplementsmodularity(isolatingchanges)andcodereusabilityasthereisnoneedtorewritetheentirefunction.SuperfunctioninPythoniscalleddynamicallybecausePythonisadynamiclanguage,unlikeotherlanguages.Superfunctioninsingleinheritance Let’staketheexampleofanimals.Dogs,cats,andcowsarepartofanimals.Theyalsosharecommoncharacteristicslike–  Theyaremammals.Theyhaveatailandfourlegs.Theyaredomesticanimals.So,theclassesdogs,cats,andhorsesareasubclassofanimalclass.Thisisanexampleofsingleinheritancebecausemanysubclassesisinheritedfromasingleparentclass.Python3#Pythonprogramtodemonstrate#superfunction classAnimals:    #Initializingconstructor    def__init__(self):        self.legs=4        self.domestic=True        self.tail=True        self.mammals=True     defisMammal(self):        ifself.mammals:            print("Itisamammal.")     defisDomestic(self):        ifself.domestic:            print("Itisadomesticanimal.") classDogs(Animals):    def__init__(self):        super().__init__()     defisMammal(self):        super().isMammal() classHorses(Animals):    def__init__(self):        super().__init__()     defhasTailandLegs(self):        ifself.tailandself.legs==4:            print("Haslegsandtail") #DrivercodeTom=Dogs()Tom.isMammal()Bruno=Horses()Bruno.hasTailandLegs()Output:Itisamammal. HaslegsandtailSuperfunctioninmultipleinheritancesLet’stakeanotherexampleofasuperfunction,Supposeaclasscanflyandcanswiminheritfromamammalclassandtheseclassesareinheritedbytheanimalclass.Sotheanimalclassinheritsfromthemultiplebaseclasses.Let’sseetheuseofPythonsuperwithargumentsinthiscasePython3classMammal():     def__init__(self,name):        print(name,"Isamammal") classcanFly(Mammal):     def__init__(self,canFly_name):        print(canFly_name,"cannotfly")         #CallingParentclass        #Constructor        super().__init__(canFly_name) classcanSwim(Mammal):     def__init__(self,canSwim_name):         print(canSwim_name,"cannotswim")         super().__init__(canSwim_name) classAnimal(canFly,canSwim):     def__init__(self,name):        super().__init__(name) #DriverCodeCarol=Animal("Dog")Output:TheclassAnimalinheritsfromtwo-parentclasses–canFlyandcanSwim.So,thesubclassinstanceCarolcanaccessbothoftheparentclassconstructors. Dogcannotfly Dogcannotswim DogIsamammalMROinMultipleInheritancePython3classA:    defage(self):        print("Ageis21")classB:    defage(self):        print("Ageis23")classC(A,B):    defage(self):        super(C,self).age()     c=C()print(C.__mro__)print(C.mro())Output:(,,,) [,,,]Multi-LevelinheritanceLet’stakeanotherexampleofasuperfunction,supposeaclasscanSwimisinheritedbycanFly,canFlyfrommammalclass.SothemammalclassinheritsfromtheMulti-Levelinheritance.Let’sseetheuseofPythonsuperwithargumentsinthiscasePython3classMammal():     def__init__(self,name):        print(name,"Isamammal")  classcanFly(Mammal):     def__init__(self,canFly_name):        print(canFly_name,"cannotfly")         #CallingParentclass        #Constructor        super().__init__(canFly_name)  classcanSwim(canFly):     def__init__(self,canSwim_name):         print(canSwim_name,"cannotswim")         super().__init__(canSwim_name)  classAnimal(canSwim):     def__init__(self,name):         #Callingtheconstructor        #ofboththeparent        #classintheorderof        #theirinheritance        super().__init__(name)  #DriverCodeCarol=Animal("Dog")Output:Dogcannotswim Dogcannotfly DogIsamammalMyPersonalNotes arrow_drop_upSave LikeNext Python|super()insingleinheritanceRecommendedArticlesPage:04,Apr1930,Apr1930,Jul2017,Jul1625,Feb1631,Jul1906,Jun1911,Jun1911,Jun1912,Jun1917,Aug1902,Sep1926,Sep1904,Mar2021,Apr2026,Apr2028,May2031,Jul2013,Aug2015,Aug2002,Jan2116,Dec2116,Dec2109,Feb16ArticleContributedBy:sathiyajith19@sathiyajith19VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:Akanksha_Raivivhonsimmytarika5varshagumber28surajkumarguptainternshlokdi35dqmahesh350nArticleTags:Python-OOPpython-oop-conceptsPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?