__init__ in Python - GeeksforGeeks

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

The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the object's state. The task of constructors is to ... 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 ▲RelatedArticles__init__inPythonselfinPythonclassClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframe__init__inPythonselfinPythonclassClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframe__init__inPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: BasicLastUpdated: 23Jun,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Prerequisites–PythonClass,Objects,SelfWheneverobject-orientedprogrammingisdoneinPython,wemostlycomeacross__init__methodinoopswhichweusuallydon’tfullyunderstand.Thisarticleexplainsthemainconceptof__init__butbeforeunderstandingthe__init__someprerequisitesarerequired.Whatis__init__inPython?TheDefault__init__ConstructorinC++andJava.Constructorsareusedtoinitializingtheobject’sstate.Thetaskofconstructorsistoinitialize(assignvalues)tothedatamembersoftheclasswhenanobjectoftheclassiscreated.Likemethods,aconstructoralsocontainsacollectionofstatements(i.e.instructions)thatareexecutedatthetimeofObjectcreation.Itisrunassoonasanobjectofaclassisinstantiated.Themethodisusefultodoanyinitializationyouwanttodowithyourobject.Example: Python3#ASampleclasswithinitmethodclassPerson:     #initmethodorconstructor    def__init__(self,name):        self.name=name     #SampleMethod    defsay_hi(self):        print('Hello,mynameis',self.name)  p=Person('Nikhil')p.say_hi()Output:Hello,mynameisNikhilUnderstandingthecodeIntheaboveexample,apersonnameNikhiliscreated.Whilecreatingaperson,“Nikhil”ispassedasanargument,thisargumentwillbepassedtothe__init__methodtoinitializetheobject.Thekeywordselfrepresentstheinstanceofaclassandbindstheattributeswiththegivenarguments.Similarly,manyobjectsofthePersonclasscanbecreatedbypassingdifferentnamesasarguments.BelowistheexampleofinitinpythonwithparametersExampleof__init__ Python3#ASampleclasswithinitmethodclassPerson:     #initmethodorconstructor    def__init__(self,name):        self.name=name     #SampleMethod    defsay_hi(self):        print('Hello,mynameis',self.name)  #Creatingdifferentobjectsp1=Person('Nikhil')p2=Person('Abhinav')p3=Person('Anshul') p1.say_hi()p2.say_hi()p3.say_hi()Output:Hello,mynameisNikhil Hello,mynameisAbhinav Hello,mynameisAnshul__init__withinheritanceInheritanceisthecapabilityofoneclasstoderiveorinheritthepropertiesfromsomeotherclass.Let’sconsiderthebelowexampletoseehow__init__worksininheritance. Python3#Pythonprogramto#demonstrateinitwith#inheritance classA(object):    def__init__(self,something):        print("Ainitcalled")        self.something=something  classB(A):    def__init__(self,something):        #Callinginitofparentclass        A.__init__(self,something)        print("Binitcalled")        self.something=something  obj=B("Something")Output:Ainitcalled BinitcalledSo,theparentclassconstructoriscalledfirst.ButinPython,itisnotcompulsorythattheparentclassconstructorwillalwaysbecalledfirst.Theorderinwhichthe__init__methodiscalledforaparentorachildclasscanbemodified.Thiscansimplybedonebycallingtheparentclassconstructorafterthebodyofthechildclassconstructor. Example: Python3#Pythonprogramto#demonstrateinitwith#inheritance classA(object):    def__init__(self,something):        print("Ainitcalled")        self.something=something  classB(A):    def__init__(self,something):        print("Binitcalled")        self.something=something        #Callinginitofparentclass        A.__init__(self,something)  obj=B("Something")Output:Binitcalled AinitcalledNote:Toknowmoreaboutinheritanceclickhere.MyPersonalNotes arrow_drop_upSave LikeNext selfinPythonclassRecommendedArticlesPage:15,Apr1925,Feb1631,Jul1906,Jun1911,Jun1911,Jun1912,Jun1917,Aug1902,Sep1926,Sep1904,Mar2021,Apr2026,Apr2028,May2031,Jul2013,Aug2015,Aug2002,Jan2116,Dec2116,Dec2109,Feb1603,Jan2128,Oct2124,Jul18ArticleContributedBy:nikhilaggarwal3@nikhilaggarwal3VotefordifficultyCurrentdifficulty: BasicEasy Normal Medium Hard ExpertImprovedBy:surajkumarguptainternArticleTags:Python-OOPPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?