Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Python

Understanding Self and __init__ Method in Python Class

2022-07-18

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 :

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