__init__ in Python: An Overview | Udacity

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

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time ... Programs ArtificialIntelligence NanodegreePrograms MachineLearningEngineerforMicrosoftAzure AIforHealthcare Intel®EdgeAIforIoTDevelopers MachineLearningEngineer AIProductManager AIProgrammingwithPython DeepLearning IntrotoMachineLearningwithPyTorch IntrotoMachineLearningwithTensorFlow DataStructuresandAlgorithms ArtificialIntelligenceforTrading ComputerVision NaturalLanguageProcessing DeepReinforcementLearning ArtificialIntelligence AIforBusinessLeaders AutonomousSystems NanodegreePrograms SelfDrivingCarEngineer IntrotoSelf-DrivingCars RoboticsSoftwareEngineer C++ DataStructuresandAlgorithms FlyingCarandAutonomousFlightEngineer SensorFusionEngineer Business NanodegreePrograms ActivationandRetentionStrategy AgileSoftwareDevelopment DataScienceforBusinessLeaders MonetizationStrategy GrowthProductManager DataProductManager SQL ProductManager PredictiveAnalyticsforBusiness DigitalMarketing MarketingAnalytics AIforBusinessLeaders AIProductManager BusinessAnalytics DataVisualization UXDesigner CloudComputingforBusinessLeaders CloudComputing NanodegreePrograms HybridCloudEngineer CloudDeveloperusingMicrosoftAzure CloudDevOpsusingMicrosoftAzure AWSCloudArchitect CloudDeveloper CloudDevOpsEngineer Cybersecurity NanodegreePrograms IntroductiontoCybersecurity SecurityEngineer SecurityAnalyst EthicalHacker DataScience NanodegreePrograms DataArchitect DataProductManager SQL DataAnalyst PredictiveAnalyticsforBusiness DataScientist DataEngineer MarketingAnalytics BusinessAnalytics ProgrammingforDataSciencewithPython ProgrammingforDataSciencewithR DataVisualization DataStructuresandAlgorithms DataStreaming DataScienceforBusinessLeaders DataAnalysisandVisualizationwithPowerBI ProgrammingandDevelopment NanodegreePrograms IntermediatePython RPADeveloperwithUiPath AgileSoftwareDevelopment IntermediateJavaScript JavaWebDeveloper IntroductiontoProgramming iOSDeveloper FrontEndWebDeveloper FullStackWebDeveloper React DataEngineer BlockchainDeveloper C++ DataStructuresandAlgorithms AndroidKotlinDeveloper AndroidBasics AWSCloudArchitect CloudDeveloper CloudDevOpsEngineer JavaProgramming FullStackJavaScriptDeveloper Career FullCatalog Careers CareerPrep StudentSuccess BecomeAMentor BecomeAnInstructor ForEnterprise Overview OurApproach Solution Resources CorporateSocialResponsibility AboutUs ForGovernment SignIn GetStarted __init__inPython:AnOverview November3,2021 | 5minread AlexeyKlochay Back __init__inPython:AnOverview Share Today,aprogrammerisboundtocomeacrossobject-orientedprogramming(OOP)duringtheircareer.Asamodernprogramminglanguage,Pythonprovidesallthemeanstoimplementtheobject-orientedphilosophy.The__init__methodisatthecoreofOOPandisrequiredtocreateobjects. Inthisarticle,we’llreviewtheparadigmofobject-orientedprogrammingbeforeexplainingwhyandhowtousethe__init__method.  WhatIsObject-OrientedProgramming? Object-orientedprogramming(OOP)isaprogrammingpatternthatconsistsindefiningobjectsandinteractingwiththem.Anobjectisacollectionofcomplexvariablesandfunctionsandcanbeusedtorepresentrealentitieslikeabutton,anairplane,oraperson. Todeclare,initialize,andmanipulateobjectsinPython,weuseclasses.Theyserveastemplates fromwhichobjectsarecreated.Thefollowingdiagramillustratesthisidea: Wecanseeintheabovediagramthatthedogclasscontainsspecificdogcharacteristics,suchasbreedandeyecolor,aswellastheabilitiestorunandwalk.Let’sstartbydefiningaclassinPython. WhatIsaClass? Aclassdefinesandstructuresalloftheobjectsthatarecreatedfromit.Youcanviewtheclassasanobjectfactory.Let’staketheexampleofafoxterrier—abreedofdog.FromanOOPstandpoint,youcanthinkofdogasaclassthatincludesadog’scharacteristicssuchasitsbreed,oreyecolor.SinceaFoxTerrierisadog,wecancreateadogobjectthatwillinheritthecharacteristicsofitsclass.Classesusemethodsandconstructorstocreateanddefineobjects. User-DefinedAndSpecialMethods Methodsarefunctionswithinaclassthataredesignedtoperformaspecifictask.Pythondifferentiatesbetweenuser-definedmethods,writtenbytheprogrammer,andspecialmethodsthatarebuiltintothelanguage.Auser-definedmethodisafunctioncreatedbytheprogrammertoserveaspecificpurpose.Forinstance,adogclasscouldhaveawalk()methodthatthedogobjectcanuse.Theprogrammercreatesthismethodandhasitperformspecificactions. Specialmethodsareidentifiedbyadoubleunderscoreateithersideoftheirname,suchas__init__.Pythonusesspecialmethodstoenhancethefunctionalityofclasses.Mostofthemworkinthebackgroundandarecalledautomaticallywhenneededbytheprogram.Youcannotcallthemexplicitly.Forinstance,whenyoucreateanewobject,Pythonautomaticallycallsthe__new__method,whichinturncallsthe__init__method.The__str__methodiscalledwhenyouprint()anobject.Ontheotherhand,user-definedmethods,likestefi.run(),arecalledexplicitly. TheConstructor Aconstructorisaspecialmethodthattheprogramcallsuponanobject’screation.Theconstructorisusedintheclasstoinitializedatamemberstotheobject.Withourdogclassexample,youcanuseaconstructortoassigndogcharacteristicstoeachFoxTerrierobject.Thespecialmethod__init__isthePythonconstructor. Withanunderstandingofobjectorientedprogrammingandclasses,let’snowlookathowthe__init__methodworkswithinaPythonprogram. TheImportanceofObjectsinPython Wedon’talwaysseeitwhenwewriteaprogram,butobjectsarecentraltothewayPythonworks.WhenwedeclareasimplevariableinPython,anobjectiscreatedinthebackground.Ifweexecutethefollowingbitofcode: breed="Doberman" Pythonusesthestrclassthatcontainspropertiesandmethods,exactlyliketheonesyoucreateinyourowncode,exceptit’sallhappeninginthebackground. HowDoesthe__init__MethodWork?  The__init__methodisthePythonequivalentoftheC++constructorinanobject-orientedapproach.The__init__ functioniscalledeverytimeanobjectiscreatedfromaclass.The__init__methodletstheclassinitializetheobject’sattributesandservesnootherpurpose.Itisonlyusedwithinclasses.  CreateaClass Let’sbeginbycreatingaclass: classDog: def__init__(self,dogBreed,dogEyeColor): self.breed=dogBreed self.eyeColor=dogEyeColor... First,wedeclaretheclassDogusingthekeywordclass.Weusethekeyworddeftodefineafunctionormethod,suchasthe__init__method.Asyoucansee,the__init__methodinitializestwoattributes:breedandeyeColor.  We’llnowseehowtopasstheseparameterswhendeclaringanobject.Thisiswhereweneedthekeywordselftobindtheobject’sattributestotheargumentsreceived. CreateanObject Nextwe’llcreateanobject,orinstance,oftheclassDog: ...Tomita=Dog("FoxTerrier","brown")... Whenwecreatetheobjecttomita(whichisthedog’sname),wefirstdefinetheclassfromwhichitiscreated(Dog).Wenextpassthearguments“FoxTerrier”and“brown,”whichcorrespondtotherespectiveparametersofthe__init__methodoftheclassDog. The__init__methodusesthekeywordselftoassignthevaluespassedasargumentstotheobjectattributesself.breedandself.eyeColor. AccessObjectAttributes ToaccessanattributeofyourbrandnewFoxTerrierobject,youcanusethedot(.)notationtogetthevalueyouneed.Aprintstatementhelpsusdemonstratehowthisworks: ...print("Thisdogisa",tomita.breed,"anditseyesare",tomita.eyeColor) Executingtheabovecodegivesusthefollowingresult: ThisdogisaFoxTerrieranditseyesarebrown Theprogramaccessedtomita’sattributesanddisplayedthemproperly. TheDefault__init__Constructor InPython,aconstructordoesnotnecessarilyneedparameterspassedtoit.Therecanbedefaultparameters.Aconstructorwithnomandatoryparametersiscalledadefaultconstructor.Let’srewriteourclasswithadefaultconstructor: classDog: def__init__(self,dogBreed="GermanShepherd",dogEyeColor="Brown"): self.breed=dogBreed self.eyeColor=dogEyeColor Ifauserdoesnotenteranyvalues,theconstructorwillassign“GermanShepherd”and“Brown”astheattributes. WecannowcreateaninstanceofDogwithoutspecifyinganyparameter:  tomita=Dog() Sincetherearenoargumentstopass,weuseemptyparenthesesaftertheclassname.Wecanstilldisplaytheobject’sattributes: print("Thisdogisa",tomita.breed,"anditseyesare",tomita.eyeColor) Thisgivesusthefollowingoutput: ThisdogisaGermanShepherdanditseyesareBrown Thissimplecodeworksperfectly. LearnToCodeWithUdacity The__init__methodisparamounttoPython’sobject-orientedprogramming..Inthisarticle,weexplainedtheroleofthe__init__methodwithinthecontextofOOPandclassdefinition.The__init__methodisoneofthenumerousspecialmethodsbuiltintoPython,andprogrammerscanuseitwithorwithoutparametersforeachclasstheycreate. Wanttoreallytakeyourcodingskillstothenextlevel?OurIntroductiontoProgrammingNanodegreeprogramisyournextstep.We’llteachyouthefoundationsofcodingandhaveyouthinkingandproblemsolvinglikeaprogrammer! CompleteCodeExample Example1: classDog: def__init__(self,dogBreed,dogEyeColor): self.breed=dogBreed self.eyeColor=dogEyeColor tomita=Dog("FoxTerrier","brown") print("Thisdogisa",tomita.breed,"andhiseyesare",tomita.eyeColor) Example2: classDog: def__init__(self): self.nbLegs=4 tomita=Dog() print("Thisdoghas",tomita.nbLegs,"legs") Example3: classDog: def__init__(self,dogBreed="GermanShepherd",dogEyeColor="brown"): self.breed=dogBreed self.eyeColor=dogEyeColor tomita=Dog() print("Thisdogisa",tomita.breed,"andhiseyesare",tomita.eyeColor) AlexeyKlochay ViewAllPostsbyAlexeyKlochay Search PopularNanodegrees ProgrammingforDataSciencewithPython DataScientistNanodegree Self-DrivingCarEngineer DataAnalystNanodegree AndroidBasicsNanodegree IntrotoProgrammingNanodegree AIforTrading PredictiveAnalyticsforBusinessNanodegree AIForBusinessLeaders DataStructures&Algorithms SchoolofArtificialIntelligence SchoolofCyberSecurity SchoolofDataScience SchoolofBusiness SchoolofAutonomousSystems SchoolofExecutiveLeadership SchoolofProgrammingandDevelopment RelatedArticles ReintroducingtheDeepLearningNanodegreeProgramfromUdacity UdacityisexcitedtoreintroduceanupdatetoaprograminourSchoolofArtificialIntelligence:the... AI, deeplearning, deeplearningnanodegreeprogram, SchoolofArtificialIntelligence 2022’sHottestEnterpriseAITrends Inthelastfewyears,artificialintelligence(AI)incompanieshasmovedfromexperimentationandproofof... EnterpriseAITrends MachineLearningvs.DeepLearning:What’stheDifference? AccordingtoLinkedIn,between2018–2024,theglobalmachinelearningmarketisexpectedtoexpandat42.08%CAGR.... deeplearning, machinelearning, MachineLearningvs.DeepLearning 5MostIn-DemandTechSkillsof2022 Techworkersareconstantlylearningnewskillstostaycurrentintheworkplace. Whilesoftskillsare... AI, Cybersecurity, machinelearning, TechSkills [et_bloom_lockedoptin_id=”optin_4″] ClickbelowtodownloadyourpreferredCareerGuide WebDeveloperCareerGuide CloudCareerGuide DataCareerGuide RoboticsCareerGuide [/et_bloom_locked] ×



請為這篇文章評分?