The __init__ method runs immediately when an object of the class is established. This method can be used to initialize your object with some of the things you want. Note that the start and end of this name are double underlines.
code example:
#!/usr/bin/python
# Filename:class_init.py
Class Person:
def __init__ (self, name):
Self.name = Name
def sayhi (self):
Print Hello, my name is, Self.name
p = person (Swaroop)
P.sayhi ()
# This short example can also is written as person (Swaroop). Sayhi ()
(source file: code/class_init.py)
Output
$ python class_init.py
Hello, my name is Swaroop
How it works
Here, we define the __init__ method to take a parameter name (as well as the normal argument self). In this __init__, we just create a new domain, also known as name. Note that they are two different variables, although they have the same name. The dot number allows us to differentiate between them.
Most importantly, we do not specifically call the __init__ method, but when creating a new instance of a class, include the parameters in parentheses followed by the class name, which is passed to the __init__ method. This is the important point of this method.
Now, we are able to use the Self.name domain in our methods. This has been verified in the Sayhi method.
Comments to the c/java/c# programmer
The __init__ method is similar to constructor in C, C #, and Java
Introduction to __init__ methods in Python