01 / 21
★

__init__ &
Constructors

Learn how Python uses the __init__ method to initialize objects and why constructors are the foundation of object-oriented programming.

Python

What Is a Constructor?

A constructor is a special method that runs automatically when you create a new object from a class. Its job is to set up the initial state of the object: assigning values to attributes so the object is ready to use immediately.

Classes vs Objects

Class
A blueprint or template that defines what attributes and methods an object will have. It does not hold data itself.
Object
A specific instance created from a class. Each object holds its own unique data based on the blueprint.

Why __init__ Matters

class Dog (blueprint) __init__(self, name, breed) rex name="Rex" luna name="Luna" calls creates

Without __init__, every new object would start empty: no name, no data, no purpose. The __init__ method guarantees every object is properly initialized the moment it is created.

The __init__ Signature

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed
self
Always the first parameter. Refers to the specific object being created.
name, breed
Additional parameters you define. These become the object's attributes.
self.name
Stores the value on the object so it persists after __init__ finishes.

__init__ vs __new__

__init__ __new__
Purpose Initializes the object Creates the object
When Called After __new__ Before __init__
First Param self (instance) cls (class)
Returns Nothing (None) New instance
Used By You? Almost always Rarely

Understanding self

class Dog rex (self) self.name = "Rex" self.breed = "Lab" luna (self) self.name = "Luna" self.breed = "Husky" Each object has its own "self" reference

self is not a keyword: it's a convention. Python automatically passes the object being created as the first argument. Inside __init__, self.name = name attaches the value to that specific object.

Writing a Constructor: Step by Step

1
Define the class using the class keyword followed by a capitalized name.
2
Write def __init__(self, ...) as the first method inside the class. Always include self as the first parameter.
3
Add parameters for every piece of data the object needs at creation (name, age, score, etc.).
4
Assign to self: write self.param = param for each parameter to store it on the object.
5
Create objects by calling the class name with arguments: my_dog = Dog("Rex", "Lab"). Python calls __init__ for you.

Example 1: Basic Constructor

Python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

# Create two Student objects
alice = Student("Alice", 10)
bob = Student("Bob", 11)

print(alice.name)  # Alice
print(bob.grade)   # 11

Example 2: Default Values

Python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

# balance defaults to 0 if not provided
acct1 = BankAccount("Alice")
acct2 = BankAccount("Bob", 500)

print(acct1.balance)  # 0
print(acct2.balance)  # 500

Example 3: Methods + Constructor

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

r = Rectangle(5, 3)
print(r.area())  # 15

Computed Attributes in __init__

Python
class Circle:
    def __init__(self, radius):
        self.radius = radius
        self.diameter = radius * 2
        self.area = 3.14159 * radius ** 2

You can compute attributes inside __init__ based on the inputs. Here, only radius is passed in, but diameter and area are calculated and stored automatically. The formulas used: \( \text{diameter} = 2r \) and \( \text{area} = \pi r^2 \).

Inheritance: super().__init__

Python
class Animal:
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init__(self, name, indoor):
        super().__init__(name)
        self.indoor = indoor

The Object Lifecycle

ClassName() You call this __new__ Creates object __init__ Initializes it Ready! Use object What Happens When You Create an Object

When you write Dog("Rex", "Lab"), Python first allocates memory (__new__), then passes the new object to __init__ for setup, and finally returns the ready-to-use object.

Common Mistakes

✕ Forgetting self
Writing def __init__(name) without self causes a TypeError when you create the object.
✕ Not Using self.attr
Writing name = name instead of self.name = name creates a local variable that disappears.
✕ Returning a Value
Adding return value in __init__ raises a TypeError. __init__ must return None.

Constructor Summary

Concept Key Point Example
__init__ Initializes new objects def __init__(self, x):
self Refers to current instance self.x = x
Defaults Optional parameters def __init__(self, x=0):
super() Calls parent constructor super().__init__(x)
Return Must return None No return statement

Question 1 of 5

What is the primary purpose of the __init__ method in a Python class?

Question 2 of 5

What is the value of my_car.year?

Question 3 of 5

What happens if you write name = name instead of self.name = name inside __init__?

Question 4 of 5

What does super().__init__(species) do in the Dog class?

Question 5 of 5

Which of the following will cause a TypeError?