How does constructor method __init__ work in Python?

PythonServer Side ProgrammingProgramming


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

How can we use  "__init__ " ?

Let's consider that we are creating a class named Car. Car can have attributes like "color", "model", "speed" etc. and methods like "start", "accelarate", "change_ gear" and so on.


class Car(object):
       def __init__(self, model, color, speed):
             self.color = color
             self.speed = speed
             self.model = model
       def start(self):
       def accelerate(self):
       def change_gear(self, gear_type):
                print("gear changed")

So we have used the constructor __init__ method to initialize the class attributes.

Published on 25-Jan-2018 07:30:14