What is __init__?

init is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a init method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

class definition
class Student:
def init(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
creating a new object
stu1 = Student(“Sara”, “Ansh”, 22, “A2”)

In python, init is a method or constructor. It is automatically called to allocate memory when a new object or instance of a class is created. All classes have the init method.

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.

1 Like