__init__ in Python: An Overview | Udacity
文章推薦指數: 80 %
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] ×
延伸文章資訊
- 1[Python] CLASS(類別) + __init__ 用法
__init__ import os import sys import copy from functools import reduce #物件導向的程式設計 ! ''' 接下來,來介紹一個...
- 2__init__ in Python - GeeksforGeeks
The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the objec...
- 3Python 速查手冊- 6.1 __init__() - 程式語言教學誌
__init__() 方法(method) 是類別(class) 的預設方法之一,在物件導向程式設計(object-oriented programming) 中稱為建構子(constructo...
- 4Python 入門指南- 單元11 - __init__() 方法 - 程式語言教學誌
__str__(). 每一種都有特定的功能,其中的__init__() 方法就是物件(object) 建立時所執行的方法,舉例如下 class Demo: def __init__(self, ...
- 5關於Python的類別(Class)...基本篇 - 張凱喬- Medium
在python裡,就是用class 開宗明義定義一個類別名稱通常會用首字大寫的單字. 簡單範例1:建立基本屬性 class Animal(): def __init__(self, name):