Python __init__
文章推薦指數: 80 %
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
延伸文章資訊
- 1Init In Python | Python Init Class | What is Init Function - Edureka
The __init__ method can be called when an object is created from the class, and access is require...
- 2Python - Class Constructor __init__ method - DYclassroom
In this tutorial we will learn about the class __init__ method in Python. We learned about classe...
- 3Understanding self and __init__ method in python Class.
"__init__" is a reseved method in python classes. It is known as a constructor in object oriented...
- 4__init__ in Python - GeeksforGeeks
The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the objec...
- 56. Modules — Python 3.10.7 documentation
In the simplest case, __init__.py can just be an empty file, but it can also execute initializati...