__init__ in Python - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1__init__ in Python - GeeksforGeeks
The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the objec...
- 2[Python] CLASS(類別) + __init__ 用法
__init__ import os import sys import copy from functools import reduce #物件導向的程式設計 ! ''' 接下來,來介紹一個...
- 3__init__ in Python: An Overview | Udacity
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approac...
- 4【Python基礎】什麼是self?什麼是__init__?:看完文章馬上會用
(3) __init__是什麼? 就是物件在具體化的時候會把__init__(self)底下的運算邏輯等先執行一遍,在nask = ...
- 5Python中__init__的通俗解释是什么? - 知乎
__init__属于魔法函数的一种,让我们来看一下它的前世今生吧。后面介绍了其他的魔法函数:__ str__()、__ new__()、__ unicode__()、__ call__()、__...