Supercharge Your Classes With Python super()
文章推薦指數: 80 %
__init__() of the superclass ( Square ) will be called automatically. super() returns a delegate object to a parent class, so you call the method you want ...
Start Here
LearnPython
PythonTutorials→In-deptharticlesandvideocourses
LearningPaths→Guidedstudyplansforacceleratedlearning
Quizzes→Checkyourlearningprogress
BrowseTopics→Focusonaspecificareaorskilllevel
CommunityChat→LearnwithotherPythonistas
OfficeHours→LiveQ&AcallswithPythonexperts
Podcast→Hearwhat’snewintheworldofPython
Books→Roundoutyourknowledgeandlearnoffline
UnlockAllContent→
More
PythonLearningResources
PythonNewsletter
PythonJobBoard
MeettheTeam
BecomeaTutorialAuthor
BecomeaVideoInstructor
Search
Join
Sign‑In
SuperchargeYourClassesWithPythonsuper()
byKyleStratis
best-practices
intermediate
python
MarkasCompleted
Tweet
Share
Email
TableofContents
AnOverviewofPython’ssuper()Function
super()inSingleInheritance
WhatCansuper()DoforYou?
Asuper()DeepDive
super()inMultipleInheritance
MultipleInheritanceOverview
MethodResolutionOrder
MultipleInheritanceAlternatives
Asuper()Recap
Removeads
WatchNowThistutorialhasarelatedvideocoursecreatedbytheRealPythonteam.Watchittogetherwiththewrittentutorialtodeepenyourunderstanding:SuperchargeYourClassesWithPythonsuper()
WhilePythonisn’tpurelyanobject-orientedlanguage,it’sflexibleenoughandpowerfulenoughtoallowyoutobuildyourapplicationsusingtheobject-orientedparadigm.OneofthewaysinwhichPythonachievesthisisbysupportinginheritance,whichitdoeswithsuper().
Inthistutorial,you’lllearnaboutthefollowing:
TheconceptofinheritanceinPython
MultipleinheritanceinPython
Howthesuper()functionworks
Howthesuper()functioninsingleinheritanceworks
Howthesuper()functioninmultipleinheritanceworks
FreeBonus:5ThoughtsOnPythonMastery,afreecourseforPythondevelopersthatshowsyoutheroadmapandthemindsetyou’llneedtotakeyourPythonskillstothenextlevel.
AnOverviewofPython’ssuper()Function
Ifyouhaveexperiencewithobject-orientedlanguages,youmayalreadybefamiliarwiththefunctionalityofsuper().
Ifnot,don’tfear!Whiletheofficialdocumentationisfairlytechnical,atahighlevelsuper()givesyouaccesstomethodsinasuperclassfromthesubclassthatinheritsfromit.
super()alonereturnsatemporaryobjectofthesuperclassthatthenallowsyoutocallthatsuperclass’smethods.
Whywouldyouwanttodoanyofthis?Whilethepossibilitiesarelimitedbyyourimagination,acommonusecaseisbuildingclassesthatextendthefunctionalityofpreviouslybuiltclasses.
Callingthepreviouslybuiltmethodswithsuper()savesyoufromneedingtorewritethosemethodsinyoursubclass,andallowsyoutoswapoutsuperclasseswithminimalcodechanges.
Removeadssuper()inSingleInheritance
Ifyou’reunfamiliarwithobject-orientedprogrammingconcepts,inheritancemightbeanunfamiliarterm.Inheritanceisaconceptinobject-orientedprogramminginwhichaclassderives(orinherits)attributesandbehaviorsfromanotherclasswithoutneedingtoimplementthemagain.
Formeatleast,it’seasiertounderstandtheseconceptswhenlookingatcode,solet’swriteclassesdescribingsomeshapes:
classRectangle:
def__init__(self,length,width):
self.length=length
self.width=width
defarea(self):
returnself.length*self.width
defperimeter(self):
return2*self.length+2*self.width
classSquare:
def__init__(self,length):
self.length=length
defarea(self):
returnself.length*self.length
defperimeter(self):
return4*self.length
Here,therearetwosimilarclasses:RectangleandSquare.
Youcanusethemasbelow:
>>>>>>square=Square(4)
>>>square.area()
16
>>>rectangle=Rectangle(2,4)
>>>rectangle.area()
8
Inthisexample,youhavetwoshapesthatarerelatedtoeachother:asquareisaspecialkindofrectangle.Thecode,however,doesn’treflectthatrelationshipandthushascodethatisessentiallyrepeated.
Byusinginheritance,youcanreducetheamountofcodeyouwritewhilesimultaneouslyreflectingthereal-worldrelationshipbetweenrectanglesandsquares:
classRectangle:
def__init__(self,length,width):
self.length=length
self.width=width
defarea(self):
returnself.length*self.width
defperimeter(self):
return2*self.length+2*self.width
#HerewedeclarethattheSquareclassinheritsfromtheRectangleclass
classSquare(Rectangle):
def__init__(self,length):
super().__init__(length,length)
Here,you’veusedsuper()tocallthe__init__()oftheRectangleclass,allowingyoutouseitintheSquareclasswithoutrepeatingcode.Below,thecorefunctionalityremainsaftermakingchanges:
>>>>>>square=Square(4)
>>>square.area()
16
Inthisexample,Rectangleisthesuperclass,andSquareisthesubclass.
BecausetheSquareandRectangle.__init__()methodsaresosimilar,youcansimplycallthesuperclass’s.__init__()method(Rectangle.__init__())fromthatofSquarebyusingsuper().Thissetsthe.lengthand.widthattributeseventhoughyoujusthadtosupplyasinglelengthparametertotheSquareconstructor.
Whenyourunthis,eventhoughyourSquareclassdoesn’texplicitlyimplementit,thecallto.area()willusethe.area()methodinthesuperclassandprint16.TheSquareclassinherited.area()fromtheRectangleclass.
Note:Tolearnmoreaboutinheritanceandobject-orientedconceptsinPython,besuretocheckoutInheritanceandComposition:APythonOOPGuideandObject-OrientedProgramming(OOP)inPython3.
WhatCansuper()DoforYou?
Sowhatcansuper()doforyouinsingleinheritance?
Likeinotherobject-orientedlanguages,itallowsyoutocallmethodsofthesuperclassinyoursubclass.Theprimaryusecaseofthisistoextendthefunctionalityoftheinheritedmethod.
Intheexamplebelow,youwillcreateaclassCubethatinheritsfromSquareandextendsthefunctionalityof.area()(inheritedfromtheRectangleclassthroughSquare)tocalculatethesurfaceareaandvolumeofaCubeinstance:
classSquare(Rectangle):
def__init__(self,length):
super().__init__(length,length)
classCube(Square):
defsurface_area(self):
face_area=super().area()
returnface_area*6
defvolume(self):
face_area=super().area()
returnface_area*self.length
Nowthatyou’vebuilttheclasses,let’slookatthesurfaceareaandvolumeofacubewithasidelengthof3:
>>>>>>cube=Cube(3)
>>>cube.surface_area()
54
>>>cube.volume()
27
Caution:Notethatinourexampleabove,super()alonewon’tmakethemethodcallsforyou:youhavetocallthemethodontheproxyobjectitself.
HereyouhaveimplementedtwomethodsfortheCubeclass:.surface_area()and.volume().Bothofthesecalculationsrelyoncalculatingtheareaofasingleface,soratherthanreimplementingtheareacalculation,youusesuper()toextendtheareacalculation.
AlsonoticethattheCubeclassdefinitiondoesnothavean.__init__().BecauseCubeinheritsfromSquareand.__init__()doesn’treallydoanythingdifferentlyforCubethanitalreadydoesforSquare,youcanskipdefiningit,andthe.__init__()ofthesuperclass(Square)willbecalledautomatically.
super()returnsadelegateobjecttoaparentclass,soyoucallthemethodyouwantdirectlyonit:super().area().
Notonlydoesthissaveusfromhavingtorewritetheareacalculations,butitalsoallowsustochangetheinternal.area()logicinasinglelocation.Thisisespeciallyinhandywhenyouhaveanumberofsubclassesinheritingfromonesuperclass.
RemoveadsAsuper()DeepDive
Beforeheadingintomultipleinheritance,let’stakeaquickdetourintothemechanicsofsuper().
Whiletheexamplesabove(andbelow)callsuper()withoutanyparameters,super()canalsotaketwoparameters:thefirstisthesubclass,andthesecondparameterisanobjectthatisaninstanceofthatsubclass.
First,let’sseetwoexamplesshowingwhatmanipulatingthefirstvariablecando,usingtheclassesalreadyshown:
classRectangle:
def__init__(self,length,width):
self.length=length
self.width=width
defarea(self):
returnself.length*self.width
defperimeter(self):
return2*self.length+2*self.width
classSquare(Rectangle):
def__init__(self,length):
super(Square,self).__init__(length,length)
InPython3,thesuper(Square,self)callisequivalenttotheparameterlesssuper()call.ThefirstparameterreferstothesubclassSquare,whilethesecondparameterreferstoaSquareobjectwhich,inthiscase,isself.Youcancallsuper()withotherclassesaswell:
classCube(Square):
defsurface_area(self):
face_area=super(Square,self).area()
returnface_area*6
defvolume(self):
face_area=super(Square,self).area()
returnface_area*self.length
Inthisexample,youaresettingSquareasthesubclassargumenttosuper(),insteadofCube.Thiscausessuper()tostartsearchingforamatchingmethod(inthiscase,.area())atonelevelaboveSquareintheinstancehierarchy,inthiscaseRectangle.
Inthisspecificexample,thebehaviordoesn’tchange.ButimaginethatSquarealsoimplementedan.area()functionthatyouwantedtomakesureCubedidnotuse.Callingsuper()inthiswayallowsyoutodothat.
Caution:Whilewearedoingalotoffiddlingwiththeparameterstosuper()inordertoexplorehowitworksunderthehood,I’dcautionagainstdoingthisregularly.
Theparameterlesscalltosuper()isrecommendedandsufficientformostusecases,andneedingtochangethesearchhierarchyregularlycouldbeindicativeofalargerdesignissue.
Whataboutthesecondparameter?Remember,thisisanobjectthatisaninstanceoftheclassusedasthefirstparameter.Foranexample,isinstance(Cube,Square)mustreturnTrue.
Byincludinganinstantiatedobject,super()returnsaboundmethod:amethodthatisboundtotheobject,whichgivesthemethodtheobject’scontextsuchasanyinstanceattributes.Ifthisparameterisnotincluded,themethodreturnedisjustafunction,unassociatedwithanobject’scontext.
Formoreinformationaboutboundmethods,unboundmethods,andfunctions,readthePythondocumentationonitsdescriptorsystem.
Note:Technically,super()doesn’treturnamethod.Itreturnsaproxyobject.Thisisanobjectthatdelegatescallstothecorrectclassmethodswithoutmakinganadditionalobjectinordertodoso.
super()inMultipleInheritance
Nowthatyou’veworkedthroughanoverviewandsomeexamplesofsuper()andsingleinheritance,youwillbeintroducedtoanoverviewandsomeexamplesthatwilldemonstratehowmultipleinheritanceworksandhowsuper()enablesthatfunctionality.
MultipleInheritanceOverview
Thereisanotherusecaseinwhichsuper()reallyshines,andthisoneisn’tascommonasthesingleinheritancescenario.Inadditiontosingleinheritance,Pythonsupportsmultipleinheritance,inwhichasubclasscaninheritfrommultiplesuperclassesthatdon’tnecessarilyinheritfromeachother(alsoknownassiblingclasses).
I’maveryvisualperson,andIfinddiagramsareincrediblyhelpfultounderstandconceptslikethis.Theimagebelowshowsaverysimplemultipleinheritancescenario,whereoneclassinheritsfromtwounrelated(sibling)superclasses:
Adiagrammedexampleofmultipleinheritance(Image:KyleStratis)
Tobetterillustratemultipleinheritanceinaction,hereissomecodeforyoutotryout,showinghowyoucanbuildarightpyramid(apyramidwithasquarebase)outofaTriangleandaSquare:
classTriangle:
def__init__(self,base,height):
self.base=base
self.height=height
defarea(self):
return0.5*self.base*self.height
classRightPyramid(Triangle,Square):
def__init__(self,base,slant_height):
self.base=base
self.slant_height=slant_height
defarea(self):
base_area=super().area()
perimeter=super().perimeter()
return0.5*perimeter*self.slant_height+base_area
Note:Thetermslantheightmaybeunfamiliar,especiallyifit’sbeenawhilesinceyou’vetakenageometryclassorworkedonanypyramids.
Theslantheightistheheightfromthecenterofthebaseofanobject(likeapyramid)upitsfacetothepeakofthatobject.YoucanreadmoreaboutslantheightsatWolframMathWorld.
ThisexampledeclaresaTriangleclassandaRightPyramidclassthatinheritsfrombothSquareandTriangle.
You’llseeanother.area()methodthatusessuper()justlikeinsingleinheritance,withtheaimofitreachingthe.perimeter()and.area()methodsdefinedallthewayupintheRectangleclass.
Note:Youmaynoticethatthecodeaboveisn’tusinganyinheritedpropertiesfromtheTriangleclassyet.LaterexampleswillfullytakeadvantageofinheritancefrombothTriangleandSquare.
Theproblem,though,isthatbothsuperclasses(TriangleandSquare)definea.area().Takeasecondandthinkaboutwhatmighthappenwhenyoucall.area()onRightPyramid,andthentrycallingitlikebelow:
>>>>>pyramid=RightPyramid(2,4)
>>pyramid.area()
Traceback(mostrecentcalllast):
File"shapes.py",line63,in
延伸文章資訊
- 1Understanding Python super() with __init__() methods
super() lets you avoid referring to the base class explicitly, which can be nice. But the main ad...
- 2多重繼承 - iT 邦幫忙::一起幫忙解決難題,拯救IT 人的一天
從寫程式到脫離菜雞的歷練(以python為主的資處與檔案權限) 系列第18 篇 ... __init__() #super調用每個class內指定__init__ d = D() d.fc_a(...
- 3Python super() - GeeksforGeeks
Python has a reserved method called “__init__.” In Object-Oriented Programming, it is referred to...
- 4Python 繼承543 - Dboy Liao
相信寫OOP 的人對於繼承這個概念應該不陌生,Python 身為一個支援OOP 的語言,自然 ... class MiniHorse(Horse): def __init__(self, is_...
- 5用super 來讓父系幫助你· Introducing python - iampennywu
只要說super(). >>> class 父類別名稱(): def __init__(self, name): self.name = name # 注意以下「子類別」內的__init__()...