Python OOP
Constructors (__init__)
Complete lesson for Constructors (__init__) using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Constructors (__init__)
Section: Python OOP. Python constructors — __init__ initialization, default arguments, validation, overloading patterns, __new__ vs __init__, and factory class methods.
What is a constructor in Python?
- Python's everyday "constructor" is
__init__: it initializes a newly created instance. - You rarely call
__init__yourself; creating an object withClass(...)runs it automatically. __init__must returnNone. Its job is to set upself, not to return a different object.- Real-life analogy: hospital registration. When a baby is "created" as a patient, staff fill name and birth date immediately.
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
print("Registered:", self.name)
s = Student("Asha", 101)
print(s.roll) Why we need __init__
- Without
__init__, you can still create objects, but every caller must remember to set attributes manually. - Initialization in one place keeps invariants (required fields present, sensible defaults).
- Constructors document what data is required to build a valid object.
Without __init__ | With __init__ |
|---|---|
| Easy to forget attributes | Required data is passed at creation |
| Inconsistent objects | One setup path for all instances |
| Call sites repeat setup code | Setup lives in the class |
class Bad:
pass
b = Bad()
b.name = "x" # easy to forget
class Good:
def __init__(self, name):
self.name = name
g = Good("x")
print(g.name) Default arguments in __init__
- Use defaults for optional settings:
balance=0,active=True. - Never use a mutable default like
items=[]. UseNoneand create a new list inside. - Defaults make common cases short while still allowing full control.
class Playlist:
def __init__(self, title, songs=None):
self.title = title
self.songs = list(songs) if songs is not None else []
def add(self, song):
self.songs.append(song)
p1 = Playlist("Morning")
p2 = Playlist("Gym", ["track-a"])
p1.add("track-b")
print(p1.title, p1.songs)
print(p2.title, p2.songs) Validation and fail fast
- Check arguments in
__init__and raiseValueError(or similar) when data is illegal. - Failing at construction is better than discovering a half-built object later.
- Real-life: a ticket booth refuses age < 0 instead of printing a broken ticket.
class Temperature:
def __init__(self, celsius):
if celsius < -273.15:
raise ValueError("below absolute zero")
self.celsius = celsius
def fahrenheit(self):
return self.celsius * 9 / 5 + 32
t = Temperature(25)
print(round(t.fahrenheit(), 1))
try:
Temperature(-300)
except ValueError as e:
print("blocked:", e) Multiple ways to construct (overloading patterns)
- Python does not support true constructor overloading like Java.
- Use default args, optional flags, or
@classmethodfactories with clear names. - Named factories read better than a single
__init__with many mysterious parameters.
| Style | Example | When |
|---|---|---|
| Defaults | Account(name) / Account(name, 500) | Small optional differences |
| Factory classmethod | Date.from_iso("2026-10-25") | Alternate formats |
| Alternate constructor | Color.from_hex("#ff8800") | Different input types |
class Color:
def __init__(self, r, g, b):
self.r, self.g, self.b = r, g, b
@classmethod
def from_hex(cls, hex_code):
h = hex_code.lstrip("#")
r = int(h[0:2], 16)
g = int(h[2:4], 16)
b = int(h[4:6], 16)
return cls(r, g, b)
def __str__(self):
return f"rgb({self.r}, {self.g}, {self.b})"
print(Color(255, 136, 0))
print(Color.from_hex("#ff8800")) Copy-style construction
- Python has no special copy-constructor syntax; write a method or accept another instance.
- Shallow copies share nested mutable objects; deep copies duplicate the graph.
- For learning, an explicit
copy()method that buildsClass(self.x, self.y)is clear.
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def copy(self):
return Rectangle(self.w, self.h)
def area(self):
return self.w * self.h
a = Rectangle(3, 4)
b = a.copy()
b.w = 10
print(a.area(), b.area()) Constructor vs ordinary method
| Point | __init__ | Ordinary method |
|---|---|---|
| When it runs | During object creation | When you call it later |
| Name | Fixed special name | Any valid name |
| Return | Must return None | May return any value |
| Purpose | Initialize state | Provide behaviour |
| Called as | Class(...) | obj.method(...) |
Initialization order sketch
- Calling
Class(args)typically: create instance (__new__), then initialize (__init__). - Instance attributes assigned in
__init__are ready before the caller receives the object. - Class body runs once at definition time;
__init__runs once per instance.
print("defining class...")
class Tracer:
label = "shared"
def __init__(self, name):
print("init", name)
self.name = name
print("creating...")
t1 = Tracer("one")
t2 = Tracer("two")
print(t1.label, t2.name) Advanced — Constructors (__init__)
__new__ vs __init__
__new__is responsible for creating (returning) a new instance; it is a static-like special method.__init__then initializes the instance__new__returned.- You customize
__new__for immutable subclasses (e.g. customtuple/str) or instance caching. Day-to-day code sticks to__init__.
class UpperStr(str):
def __new__(cls, value):
return str.__new__(cls, str(value).upper())
u = UpperStr("hello")
print(u)
print(type(u).__name__) Immutable-style objects
- Set all fields in
__init__and avoid public setters if the object should not change. @dataclass(frozen=True)can enforce immutability (stdlib dataclasses).- Immutability makes objects safer to share and use as dict keys if they are hashable.
class Money:
def __init__(self, amount, currency="INR"):
if amount < 0:
raise ValueError("amount cannot be negative")
self._amount = amount
self._currency = currency
@property
def amount(self):
return self._amount
@property
def currency(self):
return self._currency
def __str__(self):
return f"{self._currency} {self._amount}"
m = Money(100)
print(m)
print(m.amount) Factory methods vs fat __init__
- A fat
__init__with many optional modes becomes hard to read and test. - Prefer small
__init__plus named@classmethodconstructors. - Factories can return subclasses or cached instances when needed.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
@classmethod
def guest(cls):
return cls("Guest", "guest@example.com")
@classmethod
def from_pair(cls, pair):
name, email = pair.split("<")
return cls(name.strip(), email.rstrip(">").strip())
print(User.guest().email)
print(User.from_pair("Asha <asha@example.com>").name) Avoid shared mutable defaults
- Default argument values are evaluated once at function definition time.
- A default
[]or{}is shared across calls — a classic bug in__init__too. - Pattern:
def __init__(self, items=None): self.items = list(items or []).
class BadBag:
def __init__(self, tags=[]):
self.tags = tags
a = BadBag()
b = BadBag()
a.tags.append("x")
print("bad b.tags", b.tags)
class GoodBag:
def __init__(self, tags=None):
self.tags = list(tags) if tags is not None else []
c = GoodBag()
d = GoodBag()
c.tags.append("x")
print("good d.tags", d.tags) Partial construction and helpers
- Keep
__init__focused; move heavy parsing to helpers or factories. - If setup can fail (network, files), prefer an explicit factory that can raise before returning.
- Do not start background threads inside
__init__unless the class is clearly a lifecycle manager.
Tricky Interview Points
Q1) What is __init__ in Python?
Answer The initializer special method that sets up a new instance after it is created. It is what most people mean by "constructor".
Q2) Does __init__ create the object?
Answer No. Creation is handled by __new__. __init__ initializes the already created instance and should return None.
Q3) Can Python overload constructors?
Answer Not by multiple __init__ definitions. Use defaults, optional args, or @classmethod alternate constructors.
Q4) Why is def __init__(self, items=[]): dangerous?
Answer The empty list is created once and shared across instances, so mutations leak between objects.
Q5) What should __init__ return?
Answer Nothing useful — implicitly None. Returning a non-None value raises TypeError.
Q6) How do you validate constructor arguments?
Answer Check conditions inside __init__ and raise ValueError/TypeError early when inputs are invalid.
Q7) What is a factory classmethod?
Answer A @classmethod that builds and returns an instance, often named from_..., using alternate input formats.
Q8) When do you customize __new__?
Answer Mostly for immutable subclasses, singletons/caching, or advanced allocation control. Everyday classes use __init__ only.
Q9) How do you copy an object?
Answer Provide a copy method, accept another instance in a factory, or use copy.copy / copy.deepcopy when appropriate.
Q10) Constructor vs method — key difference?
Answer Constructors run at creation to set state. Methods run later to perform behaviour and may return values.
Q11) Can __init__ call other methods?
Answer Yes, but avoid calling methods that subclasses may override in fragile ways; keep initialization simple.
Q12) Real-life example of a constructor?
Answer Opening a bank account: the moment of creation captures account number, holder name, and opening balance.
Simple Programs
Coffee order with defaults
class Coffee:
def __init__(self, size="M", sugar=1, milk=True):
self.size = size
self.sugar = sugar
self.milk = milk
def __str__(self):
milk = "milk" if self.milk else "no milk"
return f"Coffee {self.size}, sugar={self.sugar}, {milk}"
print(Coffee())
print(Coffee("L", 0, False))
print(Coffee(size="S", sugar=2)) Train ticket with validation
class TrainTicket:
def __init__(self, passenger, age, seat="Sleeper"):
if not passenger:
raise ValueError("passenger required")
if age < 0 or age > 120:
raise ValueError("invalid age")
self.passenger = passenger
self.age = age
self.seat = seat
def __str__(self):
return f"{self.passenger} ({self.age}) - {self.seat}"
print(TrainTicket("Ravi", 28))
print(TrainTicket("Asha", 17, "Chair Car"))
try:
TrainTicket("", 20)
except ValueError as e:
print("error:", e) Rectangle with square factory
class Rectangle:
def __init__(self, width, height):
if width <= 0 or height <= 0:
raise ValueError("sides must be positive")
self.width = width
self.height = height
@classmethod
def square(cls, side):
return cls(side, side)
def area(self):
return self.width * self.height
print(Rectangle(3, 4).area())
print(Rectangle.square(5).area()) User guest and parse factories
class User:
def __init__(self, name, role="member"):
self.name = name
self.role = role
@classmethod
def guest(cls):
return cls("Guest", "guest")
@classmethod
def admin(cls, name):
return cls(name, "admin")
for u in (User("Meena"), User.guest(), User.admin("Root")):
print(u.name, "->", u.role) Playlist avoiding mutable default bug
class Playlist:
def __init__(self, name, tracks=None):
self.name = name
self.tracks = list(tracks) if tracks is not None else []
def add(self, track):
self.tracks.append(track)
a = Playlist("A")
b = Playlist("B")
a.add("song-1")
print(a.tracks)
print(b.tracks) Temperature conversion object
class Temperature:
def __init__(self, celsius):
if celsius < -273.15:
raise ValueError("below absolute zero")
self.celsius = float(celsius)
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5 / 9)
def __str__(self):
return f"{self.celsius:.1f} C"
print(Temperature(0))
print(Temperature.from_fahrenheit(32))
print(Temperature.from_fahrenheit(98.6)) Problem Solving Tricks
- Think
__init__= "fill the form when the object is born". - Required args first, optional args with defaults after.
- Never use mutable default arguments in
__init__. - Validate early; raise clear exceptions with useful messages.
- Prefer
@classmethodfactories over a maze of boolean flags. __init__must not return a value other thanNone.- Keep
__init__short; parse messy input in helpers/factories. - Write a
copy()method when aliasing surprises your users. - Class body code runs at import/definition time;
__init__runs per instance. - If you need immutability, set private attrs and expose read-only properties.
Practice Programs List
- Write
Coffeewith defaults for size, sugar, and milk; print three orders. - Build
TrainTicketthat rejects empty names and impossible ages. - Create
Rectangle.square(side)as a classmethod factory. - Show the mutable-default bug with
tags=[], then fix it. - Add
Color.from_hexand compare withColor(r, g, b). - Write
Moneythat rejects negative amounts and exposes read-only properties. - Implement
User.guest()andUser.admin(name)factories. - Create
Temperature.from_fahrenheitand round-trip a few values. - Write a
copymethod for a class that holds a list and prove independence. - Refactor a fat
__init__with mode flags into two named factories. - Log a one-line message in
__init__and create three objects; observe order. - List five real-life "creation moments" and design an
__init__signature for each.