How does constructor method __init__ work in Python?

PythonServer Side ProgrammingProgramming

__init__ 

"__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.

Example

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

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


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