Why do we need the __init__() function in classes? What else helps?

Why do we need the __init__() function in classes? What else helps?
0

#1

What is the need of inint() function in python classes? Is there anything else that can help?


#2

init is a constructor that creates and sets up instance variables for a class. You can technically, at least I believe, create a class without it, but it’s generally useful to initialize instances of a given class.


#3

init() is what we need to initialize a class when we initiate it. Let’s take an example.

>>> class orange:
       def __init__(self):
               self.color='orange'
               self.type='citrus'
       def setsize(self,size):
               self.size=size
       def show(self):
             print(f"color: {self.color}, type: {self.type}, size: {self.size}")
>>> o=orange()
>>> o.setsize(7)
>>> o.show()

color: orange, type: citrus, size: 7

In this code, we see that it is necessary to pass the parameter ‘self’ to tell Python it has to work with this object.