__init__ &
Constructors
Learn how Python uses the __init__ method to initialize objects and why constructors are the foundation of object-oriented programming.
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
Why __init__ Matters
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
def __init__(self, name, breed):
self.name = name
self.breed = breed
__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
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
class keyword followed by a capitalized name.self as the first parameter.self.param = param for each parameter to store it on the object.my_dog = Dog("Rex", "Lab"). Python calls __init__ for you.Example 1: Basic Constructor
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
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
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__
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__
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init__(self, name, indoor):
super().__init__(name)
self.indoor = indoor
The Object Lifecycle
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
def __init__(name) without self causes a TypeError when you create the object.name = name instead of self.name = name creates a local variable that disappears.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
Consider this code:
class Car:
def __init__(self, make, year=2024):
self.make = make
self.year = year
my_car = Car("Toyota")
What is the value of my_car.year?
my_car.year equals 2024.Question 3 of 5
What happens if you write name = name instead of self.name = name inside __init__?
name = name creates a local variable inside __init__ that is discarded when the method finishes. The object never receives the attribute.Question 4 of 5
Consider this code:
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def __init__(self, species, name):
super().__init__(species)
self.name = name
d = Dog("Canine", "Rex")
What does super().__init__(species) do in the Dog class?
self.species. This allows the child class to reuse the parent's initialization logic.Question 5 of 5
Which of the following will cause a TypeError?
return 42 raises a TypeError: __init__() should return None. All other options are valid constructors.