Which method is automatically invoked when an object of a class is created in Python?

Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea of what is a class and object.

Class is a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.

In technical terms we can say that class is a blue print for individual objects with exact behaviour.

Object :

object is one of instances of the class. which can perform the functionalities which are defined in the class.

self :

self represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the class in python.

__init__ :

"__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.

How can we use  "__init__ " ?

Let's consider that you are creating a NFS game. for that we should have a car. Car can have attributes like "color", "company", "speed_limit" etc. and methods like "change_gear", "start", "accelarate", "move" etc.

class Car(object):
  """
    blueprint for car
  """

  def __init__(self, model, color, company, speed_limit):
    self.color = color
    self.company = company
    self.speed_limit = speed_limit
    self.model = model

  def start(self):
    print("started")

  def stop(self):
    print("stopped")

  def accelarate(self):
    print("accelarating...")
    "accelarator functionality here"

  def change_gear(self, gear_type):
    print("gear changed")
    " gear related functionality here"

Lets try to create different types of cars

maruthi_suzuki = Car("ertiga", "black", "suzuki", 60)
audi = Car("A6", "red", "audi", 80)

We have created two different types of car objects with the same class. while creating the car object we passed arguments  "ertiga", "black", "suzuki", 60  these arguments will pass to "__init__" method  to initialize the object. 

Here, the magic keyword "self"  represents the instance of the class. It binds the attributes with the given arguments.

Usage of "self" in class to access the methods and attributes

Case: Find out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unit

class Rectangle:
   def __init__(self, length, breadth, unit_cost=0):
       self.length = length
       self.breadth = breadth
       self.unit_cost = unit_cost
   
   def get_perimeter(self):
       return 2 * (self.length + self.breadth)
   
   def get_area(self):
       return self.length * self.breadth
   
   def calculate_cost(self):
       area = self.get_area()
       return area * self.unit_cost
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))

As we already discussed  "self" represents the same object or instance of the class. If you see, inside the method "get_area"  we have used "self.length" to get the value of the attribute "length".  attribute "length" is bind to the object(instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement  "r = Rectangle(160, 120, 2000)".  If you see the method structure "def get_area(self): "  we have used "self" as a parameter in the method because whenever we call the method  the object (instance of class) automatically passes as a first argument along with other argumets of the method.If no other arguments are provided only "self" is passed to the method. That's the reason we use "self" to call the method inside the class("self.get_area()").  we use object( instance of class) to call the method outside of the class definition("r.get_area()"). "r" is the instance of the class, when we call method "r.get_area()"  the instance "r" is passed as as first argument in the place of self.
 

r = Rectangle(160, 120, 2000)

Note: "r" is the representation of the object outside of the class and "self"  is the representation of the object inside  the class.

for more details please visit python documentation

To Know more about our Django CRM(Customer Relationship Management) Open Source Package. Check Code

At each time you create an object, the __init__ method is called.

At each time you print an object, the __str__ method is called to get.

class Point:
    def __init__(self, x = 0, y = 0):
        print('__init__')
        self.x = x
        self.y = y
    
    def __str__(self):
        print('__str__')
        return "({0},{1})".format(self.x,self.y)
>>> p = Point(3, 2)
__init__

>>> print(p)
__str__
(3,2)

>>> p
<__main__.Point at 0x7fa3ab341940>

For the last case, the __str__ method is not called but __repr__. A good practice is to override this method to create a string representation of the creation of the instance like Point(3, 2):

    def __repr__(self):
        print('__repr__')
        return f"Point({self.x}, {self.y})"
>>> p = Point(4, 6)
__init__

>>> p
__repr__
Point(4, 6)

Which method is used when an object is created from a class in Python?

Note that the __init__() method is a special type of method known as a constructor. This method is called when an object is created from the class and it allows the class to initialize the attributes of a class. Let's try this code in the live coding window below.

Which method is called when an object is created Python?

At each time you create an object, the __init__ method is called.

What method is automatically created when you create a class?

Constructor is a method that is automatically called when an object of a class is created. They provide initial values in the instance fields.

What method gets called when a class object is created?

Constructor. The constructor method is a special method for creating and initializing an object created with a class .