π§± Day 17: Constructors in Python — The First Brick of Every Object
In our previous blogs, we’ve seen how classes and objects work in Python.
But when you create an object, have you ever wondered how it knows what to start with?
That’s where constructors come in.
A constructor is a special method in Python used to initialize the state of an object when it is created.
πͺ Meet the __init__() Method
In Python, the constructor method is called __init__().
This method runs automatically whenever you create an object of a class.
As you can see, the moment d1 is created, the constructor fires — just like a welcome ritual for the new object.
π§© Why Do We Need Constructors?
Without constructors, you’d need to manually assign attributes every time you create an object. That’s messy. Constructors make the object ready-to-use as soon as it's born.
Let’s look at an example with attributes:
Now the object has a name and breed assigned right when it’s created.
No extra setup needed later.
π♂️ What is self?
In all these examples, you might have noticed the word self being passed as the first parameter.
But what is it really?
self is a reference to the current object — it allows you to access the object’s variables and methods from within the class.
Here, self.name refers to the name variable that belongs to the object.
If you don’t use self, Python won’t know which object’s data you are referring to.
So remember:
-
selfconnects the data to the object. -
It must be the first argument in every method inside the class (though you don’t pass it manually while calling the method).
π Types of Constructors
In Python, you mostly work with:
-
Default Constructor – No parameters (except
self) -
Parameterized Constructor – Takes arguments to initialize object properties
π Connecting With What You Already Know
Back when we learned about functions and classes, we saw how reusable blocks of code help reduce repetition.
Constructors are just another level — they help automate initialization, making object creation smarter and cleaner.
self? It's like the glue that holds your object together — linking its data and behavior into a single, solid unit. π― Key Takeaways
-
Constructor in Python is defined using the
__init__()method. -
It runs automatically when an object is created.
-
selfrefers to the object itself and connects its data to the class methods. -
Together,
__init__()andselfmake object creation smooth and flexible.
✅ Your Turn: Quick Challenge
Create a class Student with a constructor that takes name and marks.
Add a method to print if the student passed (marks > 40).
Try it yourself!
Tomorrow we’ll level up even more — but until then, play around with __init__() and self.
They are your first tools in mastering real-world Python classes. π§°π
Keep This In Mind:
“When a new life begins, a constructor is at work — silently setting things in place.”








Comments
Post a Comment