__ init __ in Python


 "__Init__" is a reseved method in python classes.

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when

 the object is being created.

The __init__ method is similar to constructors in C++ and Java.


The __init__() function syntax is:

def __init__(self, [arguments])

  • The def keyword is used to define it because it’s a function.
  • The first argument refers to the current object. It binds the instance to the init() method. It’s usually named “self” to follow the naming convention. You can read more about it at Python self variable.
  • The init() method arguments are optional. We can define a constructor with any number of arguments.
class Person:  
      
    # init method or constructor   
    def __init__(self, name):  
        self.name = name  
        
    def say_hi(self):  
        print('Hello, my name is', self.name)  
      
p = Person('Robert')  
p.say_hi()  

Output:
Hello, my name is Robert




Python doesn’t support multiple constructors,
unlike other popular object-oriented programming languages such as Java. We can define multiple _init_() methods but the last one will override the
earlier definitions.