Nested Classes in Python Explained with Examples

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

Let us try to get an overview of the nested class in python. A class defined in another class is known as Nested class. If an object is created ... Skiptocontent Menu Menu HellogeeksandwelcomeinthisarticlewewillcoverNestedclassesinPython.AsweareawareofthefactthatPythonisanobject-orientedprogramminglanguage.Soaclassisacoderequiredtocreateobjects.Whenaclassisinstantiatedsomeofthemagicmethodsarecalledautomatically.Wehavealreadycovereddifferentmagicmethodsindetail. Letustrytogetanoverviewofthenestedclassinpython.AclassdefinedinanotherclassisknownasNestedclass.IfanobjectiscreatedusingnestedclassthentheobjectcanalsobecreatedusingtheParentclass.Moreover,aparentclasscanhavemultiplenestedclassinit.Aswemoveaheadinthisarticlewewillcovereverythingindetail. Contents NeedofNestedClassesCreatingNestedClassesInPythonTypesofinnerclasses1.MultipleInnerClasses2.MultilevelinnerclassConclusion NeedofNestedClasses LetustrytounderstandwhyweneedNestedClasses.Wehavehumansandclothes,withouthumans,thereisnoneedforclothes.SowecanconsidertheclothestobenestedclassofHumans.Withthehelpofthenestedclass,wecanhidethecodeaswell.Alsoforaprogrammer’spointofview,itiseasiertocorrelateclassesandenhanceunderstanding. CreatingNestedClassesInPython Inthissection,wewillprimarilyfocusoncreatingnestedclasses.Inordertodosoletuslookatanexample. classlanguage: def__init__(self): self.language='PYTHON' self.lg=self.specification() defshow(self): print("Language:",self.language) classspecification: def__init__(self): self.type='HIGH-LEVEL' self.founded='1991' defdisplay(self): print("type:",self.type) print("Founded:",self.founded) out=language() out.show() ppool=out.lg ppool.display() Language:PYTHON type:HIGH-LEVEL Founded:1991 Hereabovewehavesuccessfullycreatedanestedclass.Nowletusgolinebylineandunderstandwehavedoneso.Soatfirst,wehavecreatedaclassnamedlanguage.Insideit,wehaveusedtheselfkeyword.TheselfKeywordisagetawaythroughwhichwecanaccesstheattributeandmethodsofourcreatedclass.Insidethelanguageclass,wehavecreatedanothernestedclasscalledspecification.Theresimilarlywehavedefinedthespecifications.Atlast,wegetourdesiredoutput. Typesofinnerclasses Theinnerclasscanfurtherbedividedintopartsthatwewillbecoveringnextindetail. 1.MultipleInnerClasses classEmploye: def__init__(self): self.name="Employe" self.intern=self.intern() self.head=self.head() defshow(self): print('EmployeList') print('Name:',self.name) classintern: def__init__(self): self.name='Smith' self.Id='657' defdisplay(self): print("Name:",self.name) print("Id:",self.Id) classhead: def__init__(self): self.name='Auba' self.Id='007' defdisplay(self): print("Name:",self.name) print("Degree:",self.Id) outer=Employe() outer.show() d1=outer.intern d2=outer.head print() d1.display() print() d2.display() Output: EmployeList Name:Employe Name:Smith Id:657 Name:Auba Degree:007 AclassthathasmorethenoneinnerclassinsideitiscalledMultipleInnerclass.Abovewehavesuccessfullyimplementedit.HeretheEmployeclassisourouterclass.Insidewhichwehavecreated2subclasses.OnegoesbythenameoftheInternandtheotherbythenameofthehead. 2.Multilevelinnerclass classmulti: def__init__(self): self.inner=self.Inner() self.innerinner=self.inner.InnerInner() defshow(self): print("ThisisOuterclass") ##innerclass classInner: def__init__(self): self.innerinner=self.InnerInner() defshow_classes(self): print("ThisisInnerclass") print(self.innerinner) classInnerInner: definner_display(self,msg): print("InnerInnerclass") print(msg) definner_display(self,msg): print("ThisisInnerclass") print(msg) outer=multi() outer.show() inner=multi.Inner() innerinner=inner.InnerInner() innerinner.inner_display("completed") Output: ThisisOuterclass InnerInnerclass completed Amultilevelclasscanbeunderstoodasaclassthathasaninnerclass.Also,theinnerclasshasaninnerclass.Fromthecode,youcangetanideaofhowtoexecutethisparticularprocess.Bothtypesareeasytoexecuteandunderstand.Youcanusethemasperyourneed. Conclusion Inthisarticle,wecoverednestedclassesinPython.Welookedattheneedfornestedclassesinprogramming.Thenwealsolookedathowtoimplementthenestedclassthroughanexample.Wealsolookedatthedifferenttypeofnestedclasses. Ihopethisarticlewasabletoclearalldoubts.Butincaseyouhaveanyunsolvedqueriesfeelfreetowritethembelowinthecommentsection.Donereadingthis,whynotreadaboutgetpassnext. Subscribe Login Notifyof newfollow-upcomments newrepliestomycomments Label {} [+] Name* Email* Website Label {} [+] Name* Email* Website 4Comments Oldest Newest MostVoted InlineFeedbacks Viewallcomments shri 1yearago Canwehaveanestedstaticclassintheclassmethod? 0 Reply Admin PratikKinage 1yearago Replyto  shri Yes.Sincethemethodsofanestedclasscannotdirectlyaccesstheinstanceattributesoftheouterclass.Thenestedinnerclassiskindofastaticclass. Regards, Pratik 0 Reply jeobeko 1yearago classEmploye:     def__init__(self):         self.name="Employe" requiresoutputtobe EmployeList Name:Employe#thisisFacebookinyourexample Name:Smith Id:657 Name:Auba Degree:007 0 Reply Admin PratikKinage 1yearago Replyto  jeobeko Thankyouforpointingitout.I’veupdateditaccordingly. 0 Reply   wpDiscuz AboutusPythonPoolisaplatformwhereyoucanlearnandbecomeanexpertineveryaspectofPythonprogramminglanguageaswellasinAI,ML,andDataScience. QuickLinks Algorithm Books Career Comparison DataScience Error Howto IDE&Editor Learning MachineLearning Matplotlib Module News Numpy OpenCV Pandas Programs Project PySpark Questions Review Software Tensorflow Tkinter Tutorials JoinusonTelegram wpDiscuzInsert



請為這篇文章評分?