__init__ method in Python

Rumman Ansari   Software Engineer   2022-11-24   197 Share
☰ Table of Contents

Table of Content:


__init__ method

The __init__ method is used to initialize the object’s state and contains statements that are executed at the time of object creation.

 

Example:

class Details:
    def __init__(self, animal, group):
        self.animal = animal
        self.group = group

obj1 = Details("Crab", "Crustaceans")
print(obj1.animal, "belongs to the", obj1.group, "group.")

Output:

Crab belongs to the Crustaceans group.

We can also modify and delete objects and their properties:

Example:

class Details:
    def __init__(self, animal, group):
        self.animal = animal
        self.group = group

obj1 = Details("Crab", "Crustaceans")
obj1.animal = "Shrimp"  #Modify object property
print(obj1.animal, "belongs to the", obj1.group, "group.")

Output:

Shrimp belongs to the Crustaceans group.

Example:

class Details:
    def __init__(self, animal, group):
        self.animal = animal
        self.group = group

obj1 = Details("Crab", "Crustaceans")
del obj1    #delete object entirely
print(obj1.animal, "belongs to the", obj1.group, "group.")

Output:

Traceback (most recent call last):
  File "d:\Python \Codes\class.py", line 12, in 
    print(obj1.animal, "belongs to the", obj1.group, "group.")
NameError: name 'obj1' is not defined