Tools, FAQ, Tutorials:
'__init__()' Class Method to Initialize New Instance
What is the "__init__()" class method?
✍: FYIcenter.com
The "__init__()" class method is a special method
that will be automatically called, if you use the class name as a constructor
to create a new instance of the class.
Here are the rules you need to follow to define and use the "__init__()" class method:
1. Defining the "__init__()" method - The "__init__()" class method must be defined with the first parameter represents the newly created instance of the class, initialized already by the base class. Of course, you can have additional parameters to help you initialize the instance.
Here is the syntax of how to define the "__init__()" method:
class class_name(base_class):
class properties assignment statement
...
def __init__(self, other_parameters):
initialize instance properties
...
other method definition statement
...
The Python code below shows you a good example of the "__init__()" class method, which adds 3 new instance properties and updated the class property "nextID":
>>> class user(): ... nextID = 1 ... def __init__(self,name="Joe",age=25): ... self.id = user.nextID ... self.name = name ... self.age = age ... user.nextID = user.nextID + 1 ... ...
2. Calling the "__init__()" method implicitly - If use the class name as the instance constructor function, the "__init__()" method will be called implicitly.
Here is the syntax of how to call class name as instance constructor function:
x = class_name(other_parameters)
During the execution of the above statement, Python will call the "__init__()" method implicitly as:
x.__init__(other_parameters)
Of course, the above is equivalent to:
class_name.__init__(x,other_parameters)
The Python code below shows you how the "__init__()" class method is called which adds 3 new instance properties and updated the class property "nextID":
>>> class user():
... nextID = 1
... def __init__(self,name="Joe",age=25):
... self.id = user.nextID
... self.name = name
... self.age = age
... user.nextID = user.nextID + 1
...
>>> guest = user("Tom",22)
>>> guest.name
'Tom'
>>> guest.age
22
⇒ Manage and Use Instance Properties
2018-01-27, ∼4213🔥, 0💬
Popular Posts:
What is the Azure AD v1.0 OpenID Metadata Document? Azure AD v1.0 OpenID Metadata Document is an onl...
What is EPUB 3.0 Metadata "dcterms:modified" property? EPUB 3.0 Metadata "dcterms:modified" is a req...
What is EPUB 3.0 Metadata "dc:publisher" and "dc:rights" elements? EPUB 3.0 Metadata "dc:publisher" ...
What validation keywords I can use in JSON Schema to specifically validate JSON Array values? The cu...
How to include additional claims in Azure AD v2.0 id_tokens? If you want to include additional claim...