Python Nested & Inner Classes - DataCamp
文章推薦指數: 80 %
It is a class containing more than one inner class. You can have more than one inner class in a class. As we defined earlier, it's easy to implement multiple ... SkiptomaincontentWe'reHiringBlogBlogArticlesPodcastTutorialsCheatSheetsCategoryCategoryAboutDataCampLatestnewsaboutourproductsandteamForBusinessCategoryTechnologiesDiscovercontentbytoolsandtechnologyGitPowerBIPythonRProgrammingScalaSpreadsheetsSQLTableauCategoryTopicsDiscovercontentbydatasciencetopicsAIBigDataDataAnalysisDataEngineeringDataLiteracyDataScienceDataVisualizationDeepLearningMachineLearningWorkspaceWriteforusCategorySearchShareLinkedInFacebookTwitterCopyYouhaveprobablyheardofthenestedfunctionsinPython.Ifyouknowwhatthatmeansthenunderstandinginner/nestedclassesisnothing.WewillexploresomenewthingsintheInnerorNestedclasseshere. 1.InnerorNestedClasses InnerorNestedClassisdefinedinsideanotherclass.Seethestructureofinnerornestedclasses. ##outerclass classOuter: ##innerclass classInner: pass ##multilevelinnerclass classInnerInner: pass ##anotherinnerclass class_Inner: pass ##... pass RunandeditthecodefromthistutorialonlineOpenWorkspace2.WhyInnerClasses? Groupingoftwoormoreclasses.SupposeyouhavetwoclassesCarandEngine.EveryCarneedsanEngine.But,Enginewon'tbeusedwithoutaCar.So,youmaketheEngineaninnerclasstotheCar.Ithelpssavecode. HidingcodeisanotheruseofNestedclasses.YoucanhidetheNestedclassesfromtheoutsideworld. It'seasytounderstandtheclasses.Classesarecloselyrelatedhere.Youdon'thavetosearchfortheclassesinthecode.Theyarealltogether. InnerorNestedclassesarenotthemostcommonlyusedfeatureinPython.But,itcanbeagoodfeaturetoimplementcode.Thecodeisstraightforwardtoorganizewhenyouusetheinnerornestedclasses. 3.CodingInnerClasses Implementingtheinnerornestedclassesisnotdifficult.Youcanseethestructureofthecodehere. Youcanaccesstheinnerclassintheouterclassusingtheselfkeyword.So,youcanquicklycreateaninstanceoftheinnerclassandperformoperationsintheouterclassasyouseefit.Youcan't,however,accesstheouterclassinaninnerclass.Let'sseeanexamplebelow. classOuter: """OuterClass""" def__init__(self): ##instantiatingthe'Inner'class self.inner=self.Inner() defreveal(self): ##callingthe'Inner'classfunctiondisplay self.inner.inner_display("CallingInnerclassfunctionfromOuterclass") classInner: """InnerClass""" definner_display(self,msg): print(msg) Now,you'llmaketheinstanceoftheOuterclassandcallit'sreveal()methodtoexecutetheInnerclassmethodinner_display(). ##creatinganinstanceofthe'Outer'class outer=Outer() ##callingthe'reveal()'method outer.reveal() CallingInnerclassfunctionfromOuterclass Let'sseeanotherwaytoaccesstheinnerclass.Thiswayisalittlelessefficient. Outer().Inner().inner_display("CallingtheInnerclassmethoddirectly") CallingtheInnerclassmethoddirectly Whatifyouwanttocreateaninstanceoftheinnerclassoutsidetheouterclass?Canyoudothat?Yes,let'sseehowtomakeaninstanceoftheinnerclassoutsideoftheouterclass. outer=Outer() ##instantiatingtheinnerclass inner=outer.Inner()##inner=Outer().Inner()orinner=outer.inner inner.inner_display("JustPrintIt!") JustPrintIt! 3.1.MultipleInnerClasses Itisaclasscontainingmorethanoneinnerclass.Youcanhavemorethanoneinnerclassinaclass.Aswedefinedearlier,it'seasytoimplementmultipleinnerclasses. classOuter: """OuterClass""" def__init__(self): ##Instantiatingthe'Inner'class self.inner=self.Inner() ##Instantiatingthe'_Inner'class self._inner=self._Inner() defshow_classes(self): print("ThisisOuterclass") print(inner) print(_inner) classInner: """FirstInnerClass""" definner_display(self,msg): print("ThisisInnerclass") print(msg) class_Inner: """SecondInnerClass""" definner_display(self,msg): print("Thisis_Innerclass") print(msg) ##... Accessingtheclassesisthesameaswedidearlier.Seetheexampleforbetterunderstanding. ##instantiatingtheclasses ##'Outer'class outer=Outer() ##'Inner'class inner=outer.Inner()##inner=outer.innerorinner=Outer().Inner() ##'_Inner'class _inner=outer._Inner()##_inner=outer._outeror_inner=Outer()._Inner() ##callingthemethods outer.show_classes() print() ##'Inner'class inner.inner_display("JustPrintIt!") print() ##'_Inner'class _inner.inner_display("JustShowIt!") ThisisOuterclass <__main__.outer.innerobjectat0x0000021b37962048> <__main__.outer._innerobjectat0x0000021b37962160> ThisisInnerclass JustPrintIt! Thisis_Innerclass JustShowIt! 3.2.MultilevelInnerClasses Inmultilevelinnerclasses,theinnerclasscontainsanotherclasswhichinnerclassestothepreviousone.Youcanseethestructureofthishierarchyhere: classOuter: """OuterClass""" def__init__(self): ##instantiatingthe'Inner'class self.inner=self.Inner() ##instantiatingthemultilevel'InnerInner'class self.innerinner=self.inner.InnerInner() defshow_classes(self): print("ThisisOuterclass") print(inner) ##innerclass classInner: """FirstInnerClass""" def__init__(self): ##instantiatingthe'InnerInner'class self.innerinner=self.InnerInner() defshow_classes(self): print("ThisisInnerclass") print(self.innerinner) ##multilevelinnerclass classInnerInner: definner_display(self,msg): print("ThisismultilevelInnerInnerclass") print(msg) definner_display(self,msg): print("ThisisInnerclass") print(msg) ##... Let'sseehowtoinstantiatethemultilevelinnerclass. outer=Outer() inner=outer.Inner() ##thisis'InnerInner'classinstance innerinner=inner.InnerInner()##innerinner=Outer().Inner().InnerInner() ##let'scallitsmethodinner_display innerinner.inner_display("JustPrintIt!") ThisismultilevelInnerInnerclass JustPrintIt! Conclusion Ihopeyounowunderstandtheconceptofinnerclasses.It'snowtimeforyoutoexperimentwithnestedclasses.HappyCoding:) Ifyouwouldliketolearnmoreaboutclasses,checkoutDataCamp'sPythonObject-OrientedProgramming(OOP):Tutorial. takeDataCamp'sObject-OrientedProgramminginPythoncourse.HafeezulKareemShaikTopicsPythonLearnmoreaboutPythonIntroductiontoPythonBeginner4hours4,453,331MasterthebasicsofdataanalysisinPython.ExpandyourskillsetbylearningscientificcomputingwithNumPy.SeeDetailsRightArrowStartCourseIntermediatePythonBeginner4hours845,185LevelupyourdatascienceskillsbycreatingvisualizationsusingMatplotlibandmanipulatingDataFrameswithpandas.SeeDetailsRightArrowStartCoursePythonDataScienceToolbox(Part1)Beginner3hours333,168LearntheartofwritingyourownfunctionsinPython,aswellaskeyconceptslikescopinganderrorhandling.SeeDetailsRightArrowStartCourseSeeMoreRightArrow←BacktoTutorials
延伸文章資訊
- 1Python 中的巢狀類| D棧
Python 中的巢狀類. Python · Python Class. 創建時間: ...
- 2[Python物件導向]淺談Python類別(Class) - Learn Code With Mike
Python也提供了一個函式isinstance()來判斷類別(Class)與物件(Object)的關係,語法如下:. isinstance(object_name, class_name).
- 3Python Classes and Objects [With Examples] - Programiz
Like function definitions begin with the def keyword in Python, class definitions begin with a cl...
- 4Python Nested & Inner Classes - DataCamp
It is a class containing more than one inner class. You can have more than one inner class in a c...
- 5Inner Class in Python - GeeksforGeeks
A class defined in another class is known as an inner class or nested class. If an object is crea...