Inner Class in Python - GeeksforGeeks

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

define a show method ... a NameOfInnerClass class class NameOfInnerClass: # Constructor method of inner class def __init__(self): self. Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesInheritanceinPythonInnerClassInnerClassinPythonGeneratorsinPythonWhentouseyieldinsteadofreturninPython?ReturningMultipleValuesinPythonPythonreturnstatementImportantdifferencesbetweenPython2.xandPython3.xwithexamplesPythonKeywordsKeywordsinPython|Set2NamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingPythonStringformat()Methodf-stringsinPythonEnumerate()inPythonIterateoveralistinPythonPrintlistsinPython(5DifferentWays)TwitterInterviewQuestions|Set2TwitterInterview|Set1TwitterSentimentAnalysisusingPythonPython|SentimentAnalysisusingVADERAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeInheritanceinPythonInnerClassInnerClassinPythonGeneratorsinPythonWhentouseyieldinsteadofreturninPython?ReturningMultipleValuesinPythonPythonreturnstatementImportantdifferencesbetweenPython2.xandPython3.xwithexamplesPythonKeywordsKeywordsinPython|Set2NamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingPythonStringformat()Methodf-stringsinPythonEnumerate()inPythonIterateoveralistinPythonPrintlistsinPython(5DifferentWays)TwitterInterviewQuestions|Set2TwitterInterview|Set1TwitterSentimentAnalysisusingPythonPython|SentimentAnalysisusingVADERAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeInnerClassinPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 11May,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle PythonisanObject-OrientedProgrammingLanguage,everythinginpythonisrelatedtoobjects,methods,andproperties.Aclassisauser-definedblueprintoraprototype,whichwecanusetocreatetheobjectsofaclass.Theclassisdefinedbyusingtheclasskeyword.ExampleofclassPython3#createaGeeksforgeeksclassclassGeeksforgeeks:   gfg=10Firstofall,wehavetounderstandthe__init__()built-inmethodforunderstandingthemeaningofclasses.Whenevertheclassisbeinginitiated,amethodnamely__init__()isalwaysexecuted.An__init__()methodisusedtoassignthevaluestoobjectpropertiesortoperformtheothermethodthatisrequiredtocompletewhentheobjectiscreated.Example:classwith__init__()methodPython3#createaGeeksforgeeksclassclassGeeksforgeeks:  #constructormethod def__init__(self):   #objectattributes  self.course="Campuspreparation"  self.duration="2months"   #defineashowmethod #forprintingthecontent defshow(self):  print("Course:",self.course)  print("Duration:",self.duration) #createGeeksforgeeks#classobjectouter=Geeksforgeeks() #methodcallingouter.show()Output:Course:CampusPreparation Duration:AsperyourscheduleInnerClassinPythonAclassdefinedinanotherclassisknownasaninnerclassornestedclass.Ifanobjectiscreatedusingchildclassmeansinnerclassthentheobjectcanalsobeusedbyparentclassorrootclass.Aparentclasscanhaveoneormoreinnerclassesbutgenerallyinnerclassesareavoided.Wecanmakeourcodeevenmoreobject-orientedbyusinganinnerclass.Asingleobjectoftheclasscanholdmultiplesub-objects.Wecanusemultiplesub-objectstogiveagoodstructuretoourprogram.Example:First,wecreateaclassandthentheconstructoroftheclass.Aftercreatingaclass,wewillcreateanotherclasswithinthatclass,theclassinsideanotherclasswillbecalledaninnerclass.Python3#createaColorclassclassColor:     #constructormethod  def__init__(self):    #objectattributes    self.name='Green'    self.lg=self.Lightgreen()     defshow(self):    print("Name:",self.name)     #createLightgreenclass  classLightgreen:     def__init__(self):        self.name='LightGreen'        self.code='024avc'        defdisplay(self):        print("Name:",self.name)        print("Code:",self.code) #createColorclassobjectouter=Color() #methodcallingouter.show() #createaLightgreen#innerclassobjectg=outer.lg #innerclassmethodcallingg.display()Output:Green Name:Green LightGreen 023gfd Name:LightGreen Code:023gfdWhyinnerclass?Forthegroupingoftwoormoreclasses.Supposewehavetwoclassesremoteandbattery.Everyremoteneedsabatterybutabatterywithoutaremotewon’tbeused.So,wemaketheBatteryaninnerclasstotheRemote.Ithelpsustosavecode.Withthehelpoftheinnerclassornestedclass,wecanhidetheinnerclassfromtheoutsideworld.Hence,Hidingthecodeisanothergoodfeatureoftheinnerclass.Byusingtheinnerclass,wecaneasilyunderstandtheclassesbecausetheclassesarecloselyrelated.Wedonotneedtosearchforclassesinthewholecode,theyallarealmosttogether.ThoughinnerornestedclassesarenotusedwidelyinPythonitwillbeabetterfeaturetoimplementcodebecauseitisstraightforwardtoorganizewhenweuseinnerclassornestedclass.Syntax:#createNameOfOuterClassclass classNameOfOuterClass: #Constructormethodofouterclass def__init__(self): self.NameOfVariable=Value #createInnerclassobject self.NameOfInnerClassObject=self.NameOfInnerClass() #createaNameOfInnerClassclass classNameOfInnerClass: #Constructormethodofinnerclass def__init__(self): self.NameOfVariable=Value #createobjectofouterclass outer=NameOfOuterClass()Typesofinnerclassesareasfollows: MultipleinnerclassMultilevelinnerclassMultipleinnerclassTheclasscontainsoneormoreinnerclassesknownasmultipleinnerclasses.Wecanhavemultipleinnerclassinaclass,itiseasytoimplementmultipleinnerclasses. Example:MultipleinnerclassPython3#createouterclassclassDoctors:    def__init__(self):        self.name='Doctor'        self.den=self.Dentist()        self.car=self.Cardiologist()     defshow(self):        print('Inouterclass')        print('Name:',self.name)     #createa1stInnerclass    classDentist:        def__init__(self):            self.name='Dr.Savita'            self.degree='BDS'        defdisplay(self):            print("Name:",self.name)            print("Degree:",self.degree)     #createa2ndInnerclass    classCardiologist:        def__init__(self):            self.name='Dr.Amit'            self.degree='DM'        defdisplay(self):            print("Name:",self.name)            print("Degree:",self.degree) #createaobject#ofouterclassouter=Doctors()outer.show() #createaobject#of1stinnerclassd1=outer.den #createaobject#of2ndinnerclassd2=outer.carprint()d1.display()print()d2.display()Output:Inouterclass Name:Doctor Ininnerclass1 Name:Dr.Savita Degree:BDS Ininnerclass2 Name:Dr.Amit Degree:DMMultilevelinnerclassTheclasscontainsaninnerclassandthatinnerclassagaincontainsanotherinnerclass,thishierarchyisknownasthemultilevelinnerclass.Example:MultilevelinnerclassPython3#createaouterclassclassGeeksforgeeks:      def__init__(gfg):     #createainnerclassobject     self.inner=self.Inner()   defshow(gfg):     print('Thisisanouterclass')   #createa1stinnerclass  classInner:     def__init__(self):     #createainnerclassofinnerclassobject     self.innerclassofinner=self.Innerclassofinner()      defshow(self):    print('Thisistheinnerclass')      #createainnerclassofinner   classInnerclassofinner:                defshow(self):         print()                      defshow(self):         print('Thisisaninnerclassofinnerclass') #createaouterclassobject#i.e.Geeksforgeeksclassobjectouter=Geeksforgeeks()outer.show()print() #createainnerclassobjectgfg1=outer.innergfg1.show()print() #createainnerclassofinnerclassobjectgfg2=outer.inner.innerclassofinnergfg2.show()Output:ThisisanouterclassThisisaninnerclassThisisaninnerclassofinnerclassmeansmultilevelinnerclassMyPersonalNotes arrow_drop_upSave LikePreviousInheritanceinPythonInnerClassNext GeneratorsinPythonRecommendedArticlesPage:28,Jan2026,Nov1821,Nov1928,Apr2020,Aug2012,Aug2019,Apr2220,Aug2003,Jan2120,Feb1611,Feb1620,May1701,Apr2001,Nov1705,Apr2023,Aug2105,Apr2004,Sep1831,Aug1812,Apr2024,Jan2220,Nov1807,Jan1924,Jan19ArticleContributedBy:snigdha_yambadwar@snigdha_yambadwarVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:shiprarathore17ArticleTags:Python-OOPpython-oop-conceptsPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?