Skip to main content

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.

L1

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 with Class(...) runs it automatically.
  • __init__ must return None. Its job is to set up self, 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 attributesRequired data is passed at creation
Inconsistent objectsOne setup path for all instances
Call sites repeat setup codeSetup 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=[]. Use None and 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 raise ValueError (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 @classmethod factories with clear names.
  • Named factories read better than a single __init__ with many mysterious parameters.
StyleExampleWhen
DefaultsAccount(name) / Account(name, 500)Small optional differences
Factory classmethodDate.from_iso("2026-10-25")Alternate formats
Alternate constructorColor.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 builds Class(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 runsDuring object creationWhen you call it later
NameFixed special nameAny valid name
ReturnMust return NoneMay return any value
PurposeInitialize stateProvide behaviour
Called asClass(...)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)
L2

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. custom tuple/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 @classmethod constructors.
  • 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.
L3

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.

L4

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))
L5

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 @classmethod factories over a maze of boolean flags.
  • __init__ must not return a value other than None.
  • 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.
L6

Practice Programs List

  1. Write Coffee with defaults for size, sugar, and milk; print three orders.
  2. Build TrainTicket that rejects empty names and impossible ages.
  3. Create Rectangle.square(side) as a classmethod factory.
  4. Show the mutable-default bug with tags=[], then fix it.
  5. Add Color.from_hex and compare with Color(r, g, b).
  6. Write Money that rejects negative amounts and exposes read-only properties.
  7. Implement User.guest() and User.admin(name) factories.
  8. Create Temperature.from_fahrenheit and round-trip a few values.
  9. Write a copy method for a class that holds a list and prove independence.
  10. Refactor a fat __init__ with mode flags into two named factories.
  11. Log a one-line message in __init__ and create three objects; observe order.
  12. List five real-life "creation moments" and design an __init__ signature for each.