MemberMarch 9, 2021 at 7:28 pm13 Coins0 GemsLevel: Rookie
__init__ does the work of similar to what constructor does in Java/C++.
Now, let’s understand what constructor is. Constructors are used to initialize the object’s state. The work of a constructor is to assign values to data members of a class when object of class is created. Constructors contain bunch of statements or instructions which are carried away when an object is created. It is run as soon as an object of a class is instantiated.
def __init__(self, name):
self.name = name
print('Hello, my name is', self.name)
p = Character('Joe')
In the above example, a character name Joe is created. While creating a character, “Joe” is passed as an argument, this argument will be passed to the __init__ method to initialize the object. The keyword self represents the instance of a class and binds the attributes with the given arguments. Similarly, many objects of Character class can be created by passing different names as arguments.