What is __init__?
Question
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
It will take less than 1 minute to register for lifetime. Bonus Tip - We don't send OTP to your email id Make Sure to use your own email id for free books and giveaways
Answers ( 2 )
Object oriented languages have a concept of constructor.
Every class has an constructor where it initialises the variables defined in it.
Like methods, a constructor also contains collection of statements
(i.e. instructions) that are executed at time of Object creation.
The __init__() methods acts as a constructor in python.
This method is called when an object is created from a class and it allows the class
to initialize the attributes of the class.
The word ‘self’ is used to represent the instance of a class. By using the “self” keyword
we access the attributes and methods of the class in python.
code Example :
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(‘Swapnil’)
p.say_hi()
Output:
Hello, my name is Swapnil
__init__ method is a constructor. This is called when an object is created from the class and it allows the class to initialize the attributes of a class. When we instantiate an object, most of the time we specify the data that we want to store inside that object. We define what is done with any arguments provided at instantiation using the init method.
class MyClass():
def __init__(self, string):
self.my_attribute = string
mc = MyClass(“Hello!”)
When we instantiate our new object, Python calls the init method, passing in the object. We have now stored “Hello” in the attribute my_attribute inside our object which can be accessed by: print(mc.my_attribute)