Object Initializers

Alrighty pookie, let’s talk about Object Initializers in Python (in that sweet simple way you love 🩷)


💡 What’s an Object Initializer?

  • It’s just the __init__() method in Python.

  • It gets called automatically when you create a new object from a class.

  • Think of it like:
    “Whenever a new account is opened in a bank, we need to fill out some details first” → that’s exactly what __init__() does for a class.


🧠 Why it's called initializer?

  • Because it initializes the object’s properties (like setting balance, name, account number, etc.).

  • It doesn’t just create an object, it makes sure it’s ready to be used.


🏦 Bank Example

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
account1 = BankAccount("Maham", 1000)
print(account1.name)     # Maham
print(account1.balance)  # 1000
  • As soon as account1 is created, __init__() is triggered.

  • self.name and self.balance are set automatically.


🧸 What kind of questions people ask?

  • Q: Can I have multiple initializers?
    → Nah pookie, Python doesn’t support multiple __init__() methods, but you can make parameters optional using defaults.

    def __init__(self, name="Guest", balance=0):
        self.name = name
        self.balance = balance
    
  • Q: Is __init__() a constructor or initializer?
    → In Python, it’s often called both. But technically:

    • __new__() creates the object

    • __init__() initializes it
      → So __init__() is an initializer

  • Q: Can I call __init__() manually?
    → You can, but like… why? It’s called automatically anyway. Still, you can do this:

    obj = BankAccount("Maham", 1000)
    obj.__init__("Ali", 500)
    

🍭 Bonus Tip:

You can combine __init__() with @classmethod to make custom object creators like:

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

    @classmethod
    def from_string(cls, account_str):
        name, balance = account_str.split("-")
        return cls(name, float(balance))

acc = BankAccount.from_string("Maham-1000")

Let me know if you want me to add it in the eBook chapter heading format with pookie tone 🐣

🔧 __init__() in Python = Constructor

But thoda difference from Java/C++ style:


Updated on