Back to course

The Constructor Method (`__init__`) and Instance Attributes

Python Programming: The 0 to Hero Bootcamp

The Constructor (__init__)

The constructor is a special method named __init__ (double underscores, pronounced 'dunder init'). It is automatically called every time a new object (instance) of the class is created.

Purpose: To initialize the object's instance attributes (data specific to that object).

self Parameter (The Instance Reference)

Every method defined within a class must have self as its first parameter. self is a reference to the instance of the object calling the method.

Defining Instance Attributes

Instance attributes are created by assigning values to self.<attribute_name> inside __init__.

python class Car:

# Constructor with parameters model and year
def __init__(self, model, year, color):
    # Instance attributes (unique to each car object)
    self.model = model
    self.year = year
    self.color = color
    self.engine_running = False
    
def start_engine(self):
    self.engine_running = True
    print(f"The {self.color} {self.model}'s engine is now running.")

Creating instances requires passing arguments to init

car1 = Car('Tesla Model S', 2023, 'Red') car2 = Car('Ford Fiesta', 2018, 'Blue')

print(car1.model) # Tesla Model S car2.start_engine() print(car2.engine_running) # True