Constructors and Object Initialization in Python
A Deep Dive into __init__(), self, Parameters, and How Python Creates Objects
Python • Object-Oriented Programming • 8 min read
In our previous lessons, we explored how a class acts as a blueprint, how attributes store an object’s information, and how methods define its behavior.
Now, let’s tackle a critical question: How does an object actually come to life with its data already populated?
Imagine you are building a garden management application. You want to create multiple gardens, and every single garden needs initial data right out of the box:
- A name
- A size
- A plant count
- A watering status
Without a constructor, you might be tempted to write code like this:
class Garden:
pass
garden1 = Garden()
garden1.name = "My Garden"
garden1.size = 120
garden1.plant_count = 10
garden1.is_watered = FalseThis works for one garden, but what happens when you need to manage 100 gardens? You would have to repeat that manual assignment process 100 times. Worse yet, what if you forget an attribute on garden number 42? Your objects lose their consistent structure, leading to unpredictable bugs.
Python provides a powerful solution: object initialization using a special method called __init__().
1. What Is a Constructor?
In object-oriented programming, a constructor is the mechanism responsible for creating an object and establishing its initial state.
In Python, beginners commonly refer to __init__() as the constructor. However, there is a subtle and important technical distinction under the hood:
__new__()is responsible for actually creating and returning the new instance in memory.__init__()is responsible for initializing the instance's attributes right after it has been created.
For 99% of your everyday Python programming, you will only ever write __init__(). Python handles __new__() automatically behind the scenes.
1.1 Anatomy of __init__()
Let’s look at a basic initialization method inside a class:
Python
class Garden:
def __init__(self):
self.name = "My Garden"
self.size = 120
self.plant_count = 10Let’s break down the terminology:
def: Defines a function.__init__: The special method Python calls automatically when an object is initialized. (The double underscores are called dunder for "double underscore").self: Refers to the current object being initialized.self.name,self.size, etc.: Creates and assigns attributes belonging specifically to that object instance.
1.2 Automatic Execution
Look at how we instantiate the class:
Python
garden1 = Garden()Notice that you never wrote garden1.__init__(). Yet, Python executed the initialization method automatically.
Plaintext
Step 1 — Class Definition ──> class Garden:
Step 2 — Object Creation ──> garden1 = Garden()
Step 3 — Initialization ──> __init__(self) assigns default attributes
Step 4 — Ready Object ──> garden1 is fully initialized and ready to use2. Understanding self During Initialization
The concept of self is central to Python OOP. When you execute:
Python
garden1 = Garden(Python creates a brand-new instance in memory and passes that instance as the first argument into __init__(). Conceptually, Python is running:
Get Abdilah CH’s stories in your inbox
Join Medium for free to get updates from this writer.
Python
Garden.__init__(garden1)Therefore, inside the method:
selfbecomesgarden1self.name = "My Garden"becomesgarden1.name = "My Garden"
If you later create a second garden (garden2 = Garden()), Python repeats the process, binding self to garden2. The method code is shared, but it operates on whichever instance is currently being built.
3. Passing Information to the Constructor (Parameters)
Hardcoding "My Garden" and 120 inside the class definition isn't very useful if every garden needs to be unique. To fix this, we introduce parameters.
Python
class Garden:
def __init__(self, name, size):
self.name = name
self.size = sizeNow, the person creating the object can pass custom arguments:
Python
garden1 = Garden("My Garden", 120)
garden2 = Garden("Flower Garden", 200)4. Required Parameters vs. Default Values
Sometimes an attribute is mandatory, while other times it should have a sensible default value.
Required Parameters
Python
class Student:
def __init__(self, name, age):
self.name = name
self.age = ageIf you omit age (student1 = Student("Ahmed")), Python will raise a TypeError. This is ideal when an object cannot function without specific data.
Default Parameters
What if an initial plant count should default to zero if not provided? You can set a default value:
Python
class Garden:
def __init__(self, name, plant_count=0):
self.name = name
self.plant_count = plant_count
# Both are valid!
garden1 = Garden("My Garden", 10) # plant_count = 10
garden2 = Garden("Flower Garden") # plant_count defaults to 0Python Rule: Parameters with default values must always come after parameters without default values. Writing
def __init__(self, stock=0, name):will throw a SyntaxError.
5. Writing Robust Code: Validation and Object Invariants
A great constructor doesn’t just assign values — it ensures the object starts its life in a valid state.
Imagine creating a garden with a negative size (Garden("My Garden", -100)). That doesn't make logical sense in the real world. We can protect our application using input validation inside __init__():
Python
class Garden:
def __init__(self, name, size, plant_count=0):
if not name:
raise ValueError("Garden name cannot be empty.")
if size <= 0:
raise ValueError("Garden size must be positive.")
if plant_count < 0:
raise ValueError("Plant count cannot be negative.")
self.name = name
self.size = size
self.plant_count = plant_countBy raising a ValueError, you prevent corrupted data from ever entering your system. This guarantees your object's invariants—conditions that must remain true throughout the object's lifetime.
6. The Classic Python Trap: Mutable Default Arguments
Here is a famous Python pitfall that trips up even experienced developers when writing constructors.
Suppose you want every garden to track a list of plants. You might write:
Python
class Garden:
def __init__(self, plants=[]): # DANGER ZONE
self.plants = plantsAt first glance, this looks harmless. But watch what happens when you create two gardens:
Python
garden1 = Garden()
garden2 = Garden()
garden1.plants.append("Rose")
print(garden1.plants) # Output: ['Rose']
print(garden2.plants) # Output: ['Rose'] (Wait, why does garden2 have a rose?!)Why Did This Happen?
Default arguments in Python are evaluated once when the function is defined, not every time the function is called. That means all default instances share reference to the exact same list in memory!
The Correct Approach
Always use None as a default value for mutable types (like lists, dictionaries, or sets) and initialize a fresh object inside the constructor:
Python
class Garden:
def __init__(self, plants=None):
if plants is None:
plants = [] # Creates a brand-new list for each instance
self.plants = plantsSummary Checklist
- Constructor: The mechanism for object creation and state initialization.
__new__(): Creates and returns the raw instance in memory.__init__(): Initializes the attributes of that newly created instance (and must returnNone).self: A reference pointing to the specific instance currently being initialized.- Validation: Guarding your constructors with
ifchecks andValueErrorto enforce data integrity.







