Supercharge Your Classes With Python super()

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

__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 print(pyramid.area()) File"shapes.py",line47,inarea base_area=super().area() File"shapes.py",line38,inarea return0.5*self.base*self.height AttributeError:'RightPyramid'objecthasnoattribute'height' DidyouguessthatPythonwilltrytocallTriangle.area()?Thisisbecauseofsomethingcalledthemethodresolutionorder. Note:HowdidwenoticethatTriangle.area()wascalledandnot,aswehoped,Square.area()?Ifyoulookatthelastlineofthetraceback(beforetheAttributeError),you’llseeareferencetoaspecificlineofcode: return0.5*self.base*self.height Youmayrecognizethisfromgeometryclassastheformulafortheareaofatriangle.Otherwise,ifyou’relikeme,youmighthavescrolleduptotheTriangleandRectangleclassdefinitionsandseenthissamecodeinTriangle.area(). RemoveadsMethodResolutionOrder Themethodresolutionorder(orMRO)tellsPythonhowtosearchforinheritedmethods.Thiscomesinhandywhenyou’reusingsuper()becausetheMROtellsyouexactlywherePythonwilllookforamethodyou’recallingwithsuper()andinwhatorder. Everyclasshasan.__mro__attributethatallowsustoinspecttheorder,solet’sdothat: >>>>>>RightPyramid.__mro__ (,, ,, ) ThistellsusthatmethodswillbesearchedfirstinRightpyramid,theninTriangle,theninSquare,thenRectangle,andthen,ifnothingisfound,inobject,fromwhichallclassesoriginate. Theproblemhereisthattheinterpreterissearchingfor.area()inTrianglebeforeSquareandRectangle,anduponfinding.area()inTriangle,Pythoncallsitinsteadoftheoneyouwant.BecauseTriangle.area()expectstheretobea.heightanda.baseattribute,PythonthrowsanAttributeError. Luckily,youhavesomecontroloverhowtheMROisconstructed.JustbychangingthesignatureoftheRightPyramidclass,youcansearchintheorderyouwant,andthemethodswillresolvecorrectly: classRightPyramid(Square,Triangle): def__init__(self,base,slant_height): self.base=base self.slant_height=slant_height super().__init__(self.base) defarea(self): base_area=super().area() perimeter=super().perimeter() return0.5*perimeter*self.slant_height+base_area NoticethatRightPyramidinitializespartiallywiththe.__init__()fromtheSquareclass.Thisallows.area()tousethe.lengthontheobject,asisdesigned. Now,youcanbuildapyramid,inspecttheMRO,andcalculatethesurfacearea: >>>>>>pyramid=RightPyramid(2,4) >>>RightPyramid.__mro__ (,, ,, ) >>>pyramid.area() 20.0 YouseethattheMROisnowwhatyou’dexpect,andyoucaninspecttheareaofthepyramidaswell,thanksto.area()and.perimeter(). There’sstillaproblemhere,though.Forthesakeofsimplicity,Ididafewthingswronginthisexample:thefirst,andarguablymostimportantly,wasthatIhadtwoseparateclasseswiththesamemethodnameandsignature. Thiscausesissueswithmethodresolution,becausethefirstinstanceof.area()thatisencounteredintheMROlistwillbecalled. Whenyou’reusingsuper()withmultipleinheritance,it’simperativetodesignyourclassestocooperate.PartofthisisensuringthatyourmethodsareuniquesothattheygetresolvedintheMRO,bymakingsuremethodsignaturesareunique—whetherbyusingmethodnamesormethodparameters. Inthiscase,toavoidacompleteoverhaulofyourcode,youcanrenametheTriangleclass’s.area()methodto.tri_area().Thisway,theareamethodscancontinueusingclasspropertiesratherthantakingexternalparameters: classTriangle: def__init__(self,base,height): self.base=base self.height=height super().__init__() deftri_area(self): return0.5*self.base*self.height Let’salsogoaheadandusethisintheRightPyramidclass: classRightPyramid(Square,Triangle): def__init__(self,base,slant_height): self.base=base self.slant_height=slant_height super().__init__(self.base) defarea(self): base_area=super().area() perimeter=super().perimeter() return0.5*perimeter*self.slant_height+base_area defarea_2(self): base_area=super().area() triangle_area=super().tri_area() returntriangle_area*4+base_area Thenextissuehereisthatthecodedoesn’thaveadelegatedTriangleobjectlikeitdoesforaSquareobject,socalling.area_2()willgiveusanAttributeErrorsince.baseand.heightdon’thaveanyvalues. Youneedtodotwothingstofixthis: Allmethodsthatarecalledwithsuper()needtohaveacalltotheirsuperclass’sversionofthatmethod.Thismeansthatyouwillneedtoaddsuper().__init__()tothe.__init__()methodsofTriangleandRectangle. Redesignallthe.__init__()callstotakeakeyworddictionary.Seethecompletecodebelow. CompleteCodeExampleShow/Hide classRectangle: def__init__(self,length,width,**kwargs): self.length=length self.width=width super().__init__(**kwargs) defarea(self): returnself.length*self.width defperimeter(self): return2*self.length+2*self.width #HerewedeclarethattheSquareclassinheritsfrom #theRectangleclass classSquare(Rectangle): def__init__(self,length,**kwargs): super().__init__(length=length,width=length,**kwargs) classCube(Square): defsurface_area(self): face_area=super().area() returnface_area*6 defvolume(self): face_area=super().area() returnface_area*self.length classTriangle: def__init__(self,base,height,**kwargs): self.base=base self.height=height super().__init__(**kwargs) deftri_area(self): return0.5*self.base*self.height classRightPyramid(Square,Triangle): def__init__(self,base,slant_height,**kwargs): self.base=base self.slant_height=slant_height kwargs["height"]=slant_height kwargs["length"]=base super().__init__(base=base,**kwargs) defarea(self): base_area=super().area() perimeter=super().perimeter() return0.5*perimeter*self.slant_height+base_area defarea_2(self): base_area=super().area() triangle_area=super().tri_area() returntriangle_area*4+base_area Thereareanumberofimportantdifferencesinthiscode: **kwargsismodifiedinsomeplaces(suchasRightPyramid.__init__()):**Thiswillallowusersoftheseobjectstoinstantiatethemonlywiththeargumentsthatmakesenseforthatparticularobject. Settingupnamedargumentsbefore**kwargs:YoucanseethisinRightPyramid.__init__().Thishastheneateffectofpoppingthatkeyrightoutofthe**kwargsdictionary,sothatbythetimethatitendsupattheendoftheMROintheobjectclass,**kwargsisempty. Note:Followingthestateofkwargscanbetrickyhere,sohere’satableof.__init__()callsinorder,showingtheclassthatownsthatcall,andthecontentsofkwargsduringthatcall: Class NamedArguments kwargs RightPyramid base,slant_height Square length base,height Rectangle length,width base,height Triangle base,height Now,whenyouusetheseupdatedclasses,youhavethis: >>>>>>pyramid=RightPyramid(base=2,slant_height=4) >>>pyramid.area() 20.0 >>>pyramid.area_2() 20.0 Itworks!You’veusedsuper()tosuccessfullynavigateacomplicatedclasshierarchywhileusingbothinheritanceandcompositiontocreatenewclasseswithminimalreimplementation. RemoveadsMultipleInheritanceAlternatives Asyoucansee,multipleinheritancecanbeusefulbutalsoleadtoverycomplicatedsituationsandcodethatishardtoread.It’salsoraretohaveobjectsthatneatlyinheriteverythingfrommorethanmultipleotherobjects. Ifyouseeyourselfbeginningtousemultipleinheritanceandacomplicatedclasshierarchy,it’sworthaskingyourselfifyoucanachievecodethatiscleanerandeasiertounderstandbyusingcompositioninsteadofinheritance.Sincethisarticleisfocusedoninheritance,Iwon’tgointotoomuchdetailoncompositionandhowtowielditinPython.Luckily,RealPythonhaspublishedadeep-diveguidetobothinheritanceandcompositioninPythonthatwillmakeyouanOOPproinnotime. There’sanothertechniquethatcanhelpyougetaroundthecomplexityofmultipleinheritancewhilestillprovidingmanyofthebenefits.Thistechniqueisintheformofaspecialized,simpleclasscalledamixin. Amixinworksasakindofinheritance,butinsteadofdefiningan“is-a”relationshipitmaybemoreaccuratetosaythatitdefinesan“includes-a”relationship.Withamix-inyoucanwriteabehaviorthatcanbedirectlyincludedinanynumberofotherclasses. Below,youwillseeashortexampleusingVolumeMixintogivespecificfunctionalitytoour3Dobjects—inthiscase,avolumecalculation: classRectangle: def__init__(self,length,width): self.length=length self.width=width defarea(self): returnself.length*self.width classSquare(Rectangle): def__init__(self,length): super().__init__(length,length) classVolumeMixin: defvolume(self): returnself.area()*self.height classCube(VolumeMixin,Square): def__init__(self,length): super().__init__(length) self.height=length defface_area(self): returnsuper().area() defsurface_area(self): returnsuper().area()*6 Inthisexample,thecodewasreworkedtoincludeamixincalledVolumeMixin.ThemixinisthenusedbyCubeandgivesCubetheabilitytocalculateitsvolume,whichisshownbelow: >>>>>>cube=Cube(2) >>>cube.surface_area() 24 >>>cube.volume() 8 Thismixincanbeusedthesamewayinanyotherclassthathasanareadefinedforitandforwhichtheformulaarea*heightreturnsthecorrectvolume. Asuper()Recap Inthistutorial,youlearnedhowtosuperchargeyourclasseswithsuper().Yourjourneystartedwithareviewofsingleinheritanceandthenshowedhowtocallsuperclassmethodseasilywithsuper(). YouthenlearnedhowmultipleinheritanceworksinPython,andtechniquestocombinesuper()withmultipleinheritance.YoualsolearnedabouthowPythonresolvesmethodcallsusingthemethodresolutionorder(MRO),aswellashowtoinspectandmodifytheMROtoensureappropriatemethodsarecalledatappropriatetimes. Formoreinformationaboutobject-orientedprogramminginPythonandusingsuper(),checkouttheseresources: Officialsuper()documentation Python’ssuper()ConsideredSuperbyRaymondHettinger Object-OrientedProgramminginPython3 MarkasCompleted WatchNowThistutorialhasarelatedvideocoursecreatedbytheRealPythonteam.Watchittogetherwiththewrittentutorialtodeepenyourunderstanding:SuperchargeYourClassesWithPythonsuper() 🐍PythonTricks💌 Getashort&sweetPythonTrickdeliveredtoyourinboxeverycoupleofdays.Nospamever.Unsubscribeanytime.CuratedbytheRealPythonteam. SendMePythonTricks» AboutKyleStratis Kyleisaself-taughtdeveloperworkingasaseniordataengineeratVizitLabs.Inthepast,hehasfoundedDanqEx(formerlyNasdanq:theoriginalmemestockexchange)andEncryptidGaming. »MoreaboutKyle EachtutorialatRealPythoniscreatedbyateamofdeveloperssothatitmeetsourhighqualitystandards.Theteammemberswhoworkedonthistutorialare: Aldren GeirArne Joanna MasterReal-WorldPythonSkillsWithUnlimitedAccesstoReal Python Joinusandgetaccesstothousandsoftutorials,hands-onvideocourses,andacommunityofexpert Pythonistas: LevelUpYourPythonSkills» MasterReal-WorldPythonSkillsWithUnlimitedAccesstoReal Python Joinusandgetaccesstothousandsoftutorials,hands-onvideocourses,andacommunityofexpertPythonistas: LevelUpYourPythonSkills» WhatDoYouThink? Ratethisarticle: Tweet Share Share Email What’syour#1takeawayorfavoritethingyoulearned?Howareyougoingtoputyournewfoundskillstouse?Leaveacommentbelowandletusknow. CommentingTips:Themostusefulcommentsarethosewrittenwiththegoaloflearningfromorhelpingoutotherstudents.Gettipsforaskinggoodquestionsandgetanswerstocommonquestionsinoursupportportal.Lookingforareal-timeconversation?VisittheRealPythonCommunityChatorjointhenext“Office Hours”LiveQ&ASession.HappyPythoning! KeepLearning RelatedTutorialCategories: best-practices intermediate python RecommendedVideoCourse:SuperchargeYourClassesWithPythonsuper() KeepreadingReal Pythonbycreatingafreeaccountorsigning in: Continue» Alreadyhaveanaccount?Sign-In —FREEEmailSeries— 🐍PythonTricks💌 GetPythonTricks» 🔒Nospam.Unsubscribeanytime. AllTutorialTopics advanced api basics best-practices community databases data-science devops django docker flask front-end gamedev gui intermediate machine-learning projects python testing tools web-dev web-scraping TableofContents AnOverviewofPython’ssuper()Function super()inSingleInheritance WhatCansuper()DoforYou? Asuper()DeepDive super()inMultipleInheritance MultipleInheritanceOverview MethodResolutionOrder MultipleInheritanceAlternatives Asuper()Recap MarkasCompleted Tweet Share Email RecommendedVideoCourseSuperchargeYourClassesWithPythonsuper() Almostthere!Completethisformandclickthebuttonbelowtogaininstantaccess: × 5ThoughtsOnPythonMastery StarttheClass» 🔒Nospam.Wetakeyourprivacyseriously.



請為這篇文章評分?