My cat and My neighbor’s cat both has different name. Now we can create this name attribute at the time when we are creating the object. The main benefit is, the code will be much more shorter, clean and more readable. This can be achieved with the help of constructor.
In the above example, I have mentioned one __init__ method and mentioned it as pass, which does nothing. Now check the below code where I am initializing the name at the time of class creation. Now when object will be created, we have to give the name of that object. The name of my cat is “Tommy” and will mention it when I am creating it.
So in this way, we can also initialize the cat’s color also at the creation time, and in that way, we can make our code much more readable by making it shorter. Please check the code mentioned below:-
Now what is self in the __init__ method, please print “self” to find the answer as mentioned below:-
class Cat():
#Here Name parameter has passed when defining the compile
#by using this special __init__ method
def __init__(self,name,color):
self.name = name
self.color = color
print(self)
my_cat = Cat('Tommy','white')
Neighbor_cat = Cat('Lucy','Black')
print(my_cat)
print(Neighbor_cat)
Copy the above code and run it. I hope you have guessed correctly.