Python OOP
Python __init__ Constructor
__init__ is Python's constructor method — it runs automatically whenever you create a new object, setting up that object's starting attributes.
What __init__ Does
When you call ClassName(...), Python creates a blank object and immediately calls its __init__ method to fill in the details. This is why it is called a constructor — it constructs the object's initial state.
class Car:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
car1 = Car("Tata", "Nexon", 900000)
print(car1.brand, car1.model, car1.price)Every parameter after self becomes something you must supply when creating the object, unless you give it a default value. Inside __init__, self.name = value stores the value on that particular instance.
Default Parameter Values
Just like ordinary functions, __init__ parameters can have defaults, which makes some arguments optional when creating an object.
class Student:
def __init__(self, name, grade="Not Assigned"):
self.name = name
self.grade = grade
s1 = Student("Kabir")
s2 = Student("Meera", "A")
print(s1.grade)
print(s2.grade)Not Assigned
ANever use a mutable default like a list or dictionary directly, e.g. def __init__(self, items=[]). All objects would then share the same list. Use None and create a new list inside instead.
class Cart:
def __init__(self, items=None):
self.items = items if items is not None else []
c1 = Cart()
c1.items.append("Book")
print(c1.items)__init__ never returns a value (no return statement with data) — its only job is to set up self.
Understanding __init__ is essential before moving to inheritance, where child classes often call the parent's constructor using super().
