Python init Method

The __init__ method is a class's constructor, run automatically when an object is created so it can start life with the data it needs.

When you create an object from a class, Python looks for a special method named __init__ and calls it right away. Its job is initialization: setting up the starting attributes of the new object. The double underscores on each side mark it as a dunder (double-underscore) method, part of a group of names Python treats specially. You never call __init__ yourself; Python invokes it for you when you create the instance.

Passing data in when you create an object

Any argument you pass when creating an object is forwarded to __init__ after self. Inside the method you store those arguments as attributes so the rest of the class can use them later.

Using __init__ to set up an object

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hi, I'm {self.name} and I'm {self.age}."

p = Person("Asha", 29)
print(p.greet())   # Hi, I'm Asha and I'm 29.

Default values for parameters

You can give parameters in __init__ default values so callers may leave them out. This makes objects flexible: supply everything, or accept sensible defaults for the rest.

Default arguments in the constructor

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

    def deposit(self, amount):
        self.balance += amount
        return self.balance

acc = BankAccount("Ravi")   # balance defaults to 0
acc.deposit(500)
print(acc.owner, acc.balance)   # Ravi 500
Note: __init__ should return None; it sets up the object but does not return it. Adding a return value other than None raises a TypeError. Avoid mutable default arguments such as an empty list, because that single list would be shared across all instances.
AspectDetail
When it runsAutomatically, as soon as the object is created
First parameterself, the object being initialized
Common jobStore constructor arguments as attributes
Return valueShould be None
  • __init__ is the constructor Python calls when you create an object.
  • Its first parameter is always self.
  • Store incoming arguments as attributes with self.attribute = value.
  • Give parameters defaults to make them optional.