Constructor

Do you have someone in life who just shows up for you?

Like... you didn’t even call them,
but they knew you needed them,
and they came quietly, no drama, just there to help you

→ In object-oriented programming, the constructor is that kind of person.

It’s a special method
that shows up automatically when you create an object from a class.

Even if you don’t call it,
Python calls it for you.


In Python, the constructor is called __init__

Suppose this:

class BankAccount:
    def __init__(self, holder, balance):
        self.holder = holder
        self.balance = balance

When you do this:

acc = BankAccount("Maham", 500)

You didn't call __init__()
but it got triggered quietly 😌
and it set the values , holder and balance , for you.

So now this object acc is holding:

  • holder → "Maham"

  • balance → 500

Means → Ready to use


So, What is a Constructor?

A constructor is a special function/method in a class

It automatically runs when you create an object of that class

Its job is to set initial values or do setup work


Why is it called __init__?

Because Python doesn’t allow the same-name constructor like Java or C++ (like BankAccount())

So instead, Python made a universal name:
__init__()
which stands for “initialize” (set things up at the start)


Summary:

  • A constructor is a special method

  • Called automatically when an object is created

  • Used to initialize object properties

  • In Python, it's always written as __init__

  • You don’t need to call it manually

  • self binds data to the current object

  • You can use default values, conditions, and call other methods

  • You can’t overload it like Java, but you can handle it smartly

Updated on