super() in Python: What Does It Do? [A Complete Guide]
文章推薦指數: 80 %
When you initialize a child class in Python, you can call the super().__init__() method. This initializes the parent class object into the child class. SkiptocontentSoftware,Tech&Codingsimplified.HomeAboutResourcesCoursesSwift&iOSDataSciencePythonCoursePlatformsGraphicDesign&UI/UXAdvertiseHireMeContactMenuHomeAboutResourcesCoursesSwift&iOSDataSciencePythonCoursePlatformsGraphicDesign&UI/UXAdvertiseHireMeContactTwitter Linkedin Medium Github Youtube Home»super()inPython:WhatDoesItDo?super()inPython:WhatDoesItDo?ArtturiJalliInPython,super()methodmakesitpossibletoaccessthemembersofaparentclass.Tounderstandwhatisaparentclass,youneedtoknowwhatclassinheritancemeans.Beforejumpingintothedetails,let’sseeaquickexampleofusingthesuper()method.Forinstance:classPet(): defhello(self):print("Hello,IamaPet") classCat(Pet): defsay(self): super().hello() luna=Cat() luna.say()Output:Hello,IamaPetInthispieceofcode:ThePetclassdefinesamethodcalledhello().TheCatclassinheritsthePetclass.TheCatclassimplementsasay()methodthatcallsthehello()methodfromthePetclass.Thisispossibleviathesuper()method.Inthisguide,wearegoingtotakeadeeperlookathowthesuper()methodworksinPython.Totrulyunderstandsuper(),youneedtounderstandwhatisinheritanceinPython.ClassInheritanceinPython:AQuickIntroductionPythonisanobject-orientedprogramminglanguage.Oneofthemainfeaturesofanobject-orientedlanguagelikePythonisclassinheritance.Pythonsupportsclassinheritance,alsocalledsubclassing.Theideabehindtheclassinheritanceistocreateaparentclass-childclasshierarchy.Inotherwords,themembersoftheparentclassareinheritedtothechildclass.Toputitshort,inheritanceletsyoureusecode.Butwhyreusecode?Youshouldalwaystrytoavoidrepeatingyourselfincode.SometimesyourPythonobjectsarerelatedtooneanother.Inthiscase,itwouldbeuselessifyouhadtorepeatyourselfandre-implementmethodsfromoneclasstoanotherclass.Inthiscase,youcanuseinheritance.AgreatexampleofinheritancewouldbeaPerson–Studentrelationshipinthecode.Lets’ssayyourcodehastwoclasses,PersonandStudent.Asyouknow,eachStudentisalsoaPerson.Thus,itmakessensetoinheritallthepropertiesofaPersontoanStudent.Forexample:classPerson: def__init__(self,name,age): self.name=name self.age=age defintroduce(self): print(f"Hello,mynameis{self.name}.Iam{self.age}yearsold.") classStudent(Person): def__init__(self,name,age,graduation_year): #DOnotworryaboutthenextline,wewillcomebacktoitverysoon! super().__init__(name,age) self.graduation_year=graduation_year defgraduates(self): print(f"{self.name}willgraduatein{self.graduation_year}")NowyoucanusethissetuptocreateStudentobjectsthatcanusethePersonclassesintroduce()method.Forinstance:alice=Student("Alice",30,2023) alice.introduce() alice.graduates()Output:Hello,mynameisAlice.Iam30yearsold. Alicewillgraduatein2023Inthispieceofcode:alice.introuce()iscalledfromtheparentclassofStudent,thatis,Person.alice.graduates()iscalleddirectlyfromtheStudentclassitself.Thisdemonstrateswellhowinheritanceworks.EachStudentisaPerson.ItmakessensetogivethepropertiesofaPersondirectlytotheStudent,insteadofre-implementingthemintheStudentclass.NowyouunderstandwhatinheritanceisinPython.Next,let’stakealookathowthesuper()methodworks.Thesuper()inPythonToaccessparentclasspropertiesfromthesubclass,youneedtousethesuper()method.Thesuper()isanexplicitreferencetothebaseclass.Itlinksyourparentclasstothechildclass.Anythingfoundintheparentclasscanbeaccessedinthechildclassviathesuper()method.Themostcommonexampleofusingthesuper()methodisuponinitialization.Inthepreviouschapter,youalreadysawanexampleofthis.Now,let’stakeadeeperlookathowitworks.Thesuper().__init__()CallinPythonWhenyouinitializeachildclassinPython,youcancallthesuper().__init__()method.Thisinitializestheparentclassobjectintothechildclass.Inadditiontothis,youcanaddchild-specificinformationtothechildobjectaswell.Hereiswhatitgenerallylookslike:classParent: definit(v1,v2): self.v1=v1 self.v2=v2 classChild(Parent): definit(v1,v2,v3): super().__init__(v1,v2) self.v3=v3Here:TheParentclasshaspropertiesv1andv2.Theyareinitializedintheparentclassesinit()method.TheChildclassinhertistheParentclass.TheChildclassinitializestheParentclassobjectTheChildclassalsoinitializesitselfbyspecifyinganewpropertyv3thatonlybelongstoit,nottotheParent.Let’stakealookatamoreconcreteexample.Let’ssaywehaveaclassthatrepresentsaperson.Eachpersonhasanameandage.Furthermore,eachPersonobjecthastheabilitytointroducethemselvesusingtheintroduce()method.HereiswhatthePersonclasslookslike:classPerson: def__init__(self,name,age): self.name=name self.age=age defintroduce(self): print(f"Hello,mynameis{self.name}.Iam{self.age}yearsold.")ThisclassactsasablueprintforcreatingPersonobjectsinourcode.Now,let’ssaywealsowanttorepresentstudentsinourprogram.Todothis,weneedanewclassforstudentobjects.Morespecifically,eachstudentshould:Haveaname,age,andagraduationyear.Beabletointroducethemselves.Tellwhentheyaregoingtograduate.Wecouldwriteacompletelyseparateclasslikethis:classStudent(Person): def__init__(self,name,age,graduation_year): self.name=name self.age=age self.graduation_year=graduation_year defintroduce(self): print(f"Hello,mynameis{self.name}.Iam{self.age}yearsold.") defgraduates(self): print(f"{self.name}willgraduatein{self.graduation_year}")Eventhoughthisworks,thereisaproblem.Thiscodeisnowrepetitive.Theintroduce()methodwasalreadyimplementedinthePersonclass.Also,theinit()methodlooksprettysimilar.Wecanimprovethecodebyusinginheritance.ThefirstthingtonoticeisthateachStudentisalsoaPerson,whichmakessense.ThuswecaninheritthepropertiesofaPersontotheStudentclassdirectly.Let’sthenaddanewmember,graduation_year,totheStudentobject.Inaddition,weneedamethodtodisplaythis.SowhenitcomestoinitializingtheStudentobject,wecan:InitializethePersonobjectintheStudent.Thishappenswiththesuper().__init__()call.ThisgivesthenameandagetotheStudentobject.InitializetheStudent-specificgraduationyear.HereistheimprovedversionoftheStudentclassthatutilizesinheritance.classStudent(Person): def__init__(self,name,age,graduation_year): #1.InitializethePersonobjectinStudent. super().__init__(name,age) #2.Initializethegraduation_year self.graduation_year=graduation_year #AddamethodthattellswhenthisStudentisgoingtograduate. defgraduates(self): print(f"{self.name}willgraduatein{self.graduation_year}")Paycloseattentiontothesuper().__init__(name,age)call.Thiscallsthe__init__()methodoftheparentclass,Person.Inotherwords,itinitializesaPersonobjectintotheStudentobject.Thesuper()MethodinMultipleInheritanceYoucanalsostreamlinetheprocessofinitializingmultipleclasseswiththehelpofthesuper()method.Inotherwords,youcanusethesuper()methodinmultiplesubclassestoaccessthecommonparentclassesproperties.Forinstance,let’screateahierarchysuchthataPersonobjectisinheritedtoStudentandEmployee.Hereishowitlooksincode:classPerson: def__init__(self,name,age): self.name=name self.age=age defintroduce(self): print(f"Hello,mynameis{self.name}.Iam{self.age}yearsold.") #Subclass1. classStudent(Person): def__init__(self,name,age,graduation_year): super().__init__(name,age) self.graduation_year=graduation_year defgraduates(self): print(f"{self.name}willgraduatein{self.graduation_year}") #Subclass2. classEmployee(Person): def__init__(self,name,age,start_year): super().__init__(name,age) self.start_year=start_year defgraduates(self): print(f"{self.name}startedworkingin{self.start_year}")AccessRegularInheritedMethodswithSuper()Inacoupleoflastexamples,yousawhowtousethesuper()methodtocalltheinitializeroftheparentclass.Itisimportanttonoticeyoucanaccessanyothermethodtoo.Forexample,let’smodifythePerson-Studentexampleabit.Let’screateaninfo()methodfortheStudentclass.Thismethod:Callstheintroduce()methodfromtheparentclasstointroduceitself.Showsthegraduationyear.Tocalltheintroduce()methodfromtheparentclass,usethesuper()methodtoaccessit.Hereishowitlooksincode:classPerson: def__init__(self,name,age): self.name=name self.age=age defintroduce(self): print(f"Hello,mynameis{self.name}.Iam{self.age}yearsold.") #Subclass1. classStudent(Person): def__init__(self,name,age,graduation_year): super().__init__(name,age) self.graduation_year=graduation_year definfo(self): #CallthePersonclassesintroduce()methodtointroducethisStudent. super().introduce() print(f"{self.name}willgraduatein{self.graduation_year}") alice=Student("Alice",30,2023) alice.info()Output:Hello,mynameisAlice.Iam30yearsold. Alicewillgraduatein2023Asyoucansee,nowitispossibletocalltheinfo()methodonaStudentobjecttoseetheintroductionandthegraduationyearprints.Sothesuper()methodcanbeusefulinmanywaysinPython.Thiscompletesourguide.ConclusionTodayyoulearnedwhatthesuper()methoddoesinPython.Torecap,thesuper()methodlinksaparentclasstoitschildclass.Youcanaccessallthepropertiesintheparentclassviathesuper()method.Thanksforreading.Happycoding!FurtherReading50PythonInterviewQuestionsTools&ResourcesforSoftwareDevelopersUsethesewonderfultoolstoincreasemotivation,productivity,andonlinesecurity.ReadMoreShareShareontwitterShareonlinkedinShareonfacebookShareonpinterestShareonemailartturijalliHi,I'mArtturi! I'manentrepreneurandabloggerfromFinland.Mygoalistomakecodingandtecheasierforyou.AllPosts»PrevPreviousLazyVariablesinSwiftwithExamples[Updatedin2022]NextCodableinSwift:JSONParsingMadeEasy[in2022]NextArtturiJalliLet’sconnectonLinkedInHomeAboutResourcesSponsorshipContactAffiliateDisclaimerPrivacyPolicyMenuHomeAboutResourcesSponsorshipContactAffiliateDisclaimerPrivacyPolicyLinkedin Medium Github Apple Youtube x
延伸文章資訊
- 1Python super() - GeeksforGeeks
Python has a reserved method called “__init__.” In Object-Oriented Programming, it is referred to...
- 2多重繼承 - iT 邦幫忙::一起幫忙解決難題,拯救IT 人的一天
從寫程式到脫離菜雞的歷練(以python為主的資處與檔案權限) 系列第18 篇 ... __init__() #super調用每個class內指定__init__ d = D() d.fc_a(...
- 3Python 繼承543 - Dboy Liao
相信寫OOP 的人對於繼承這個概念應該不陌生,Python 身為一個支援OOP 的語言,自然 ... class MiniHorse(Horse): def __init__(self, is_...
- 4[Day33] python的super繼承 - iT 邦幫忙
子類別的創建需要放入父類別的名稱為引數,創造繼承作用即 class subclass_name(superclass_name):; super().__init__ 會去呼叫父類別的initi...
- 5用super 來讓父系幫助你· Introducing python - iampennywu
只要說super(). >>> class 父類別名稱(): def __init__(self, name): self.name = name # 注意以下「子類別」內的__init__()...