Python __init__

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

In this tutorial, you'll learn how to use the Python __init__() method to initialize objects. SkiptocontentHome»PythonOOP»Python__init__Summary:inthistutorial,you’lllearnhowtousethePython__init__()methodtoinitializeobject’sattributes.IntroductiontothePython__init__()methodWhenyoucreateanewobjectofaclass,Pythonautomaticallycallsthe__init__()methodtoinitializetheobject’sattributes.Unlikeregularmethods,the__init__()methodhastwounderscores(__)oneachside.Therefore,the__init__()isoftencalleddunderinit.Thenamecomesabbreviationofthedoubleunderscoresinit.Thedoubleunderscoresatbothsidesofthe__init__()methodindicatethatPythonwillusethemethodinternally.Inotherwords,youshouldnotexplicitlycallthismethod.SincePythonwillautomaticallycallthe__init__()methodimmediatelyaftercreatinganewobject,youcanusethe__init__()methodtoinitializetheobject’sattributes.ThefollowingdefinesthePersonclasswiththe__init__()method:classPerson: def__init__(self,name,age): self.name=name self.age=age if__name__=='__main__': person=Person('John',25) print(f"I'm{person.name}.I'm{person.age}yearsold.") Codelanguage:Python(python)WhenyoucreateaninstanceofthePersonclass,Pythonperformstwothings:First,createanewinstanceofthePersonclassbysettingtheobject’snamespacesuchas__dict__attributetoempty({}).Second,callthe__init__methodtoinitializetheattributesofthenewlycreatedobject.Notethatthe__init__methoddoesn’tcreatetheobjectbutonlyinitializestheobject’sattributes.Hence,the__init__()isnotaconstructor.Ifthe__init__hasparametersotherthantheself,youneedtopassthecorrespondingargumentswhencreatinganewobjectliketheexampleabove.Otherwise,you’llgetanerror.The__init__methodwithdefaultparametersThe__init__()method’sparameterscanhavedefaultvalues.Forexample:classPerson: def__init__(self,name,age=22): self.name=name self.age=age if__name__=='__main__': person=Person('John') print(f"I'm{person.name}.I'm{person.age}yearsold.") Output:I'mJohn.I'm22yearsold.Codelanguage:JavaScript(javascript)Inthisexample,theageparameterhasadefaultvalueof22.Becausewedon’tpassanargumenttothePerson(),theageusesthedefaultvalue.SummaryUsethe__init__()methodtoinitializetheobject’sattributes.The__init__()doesn’tcreateanobjectbutisautomaticallycalledaftertheobjectiscreated.PreviouslyPythonMethodsUpNextPythonInstanceVariablesSearchfor:Classes&ObjectsSpecialMethodsPropertySingleInheritanceEnumerationsSOLIDPrinciplesMultipleInheritanceDescriptorsMetaProgrammingExceptions



請為這篇文章評分?