The __init__() Constructor Function
All classes have the built-in constructor _init_() function that is always executed when a class is being initiated.
obj_name = className()
This is invoked automatically to set a newly created object’s attributes to their initial (default) state.
We can add any number parameters to the constructor (after self). This is optional.
class className():
# initalize
def __init__(self, attribute1,...):
self.attribute1 = attribute1
...
...
These arguments are generally used to initialize the instance variables.
Example:
Create a class named Person, use the __init__() function to assign initial values for name and use it in a method.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil
The __init__() function is called automatically every time the class is being used to create a new object.