Lesson · Object-Oriented Python
Constructors & Initialization
55 min readConstructors & Initialization
Object construction and initialization are separate steps represented by `__new__` and `__init__`. Most application classes customize initialization, while immutable or metaclass-heavy designs sometimes need `__new__`.
Learning goals
- Explain the division of labor between
__new__(create and return the instance) and__init__(configure it and returnNone). - Read
PositiveInt("12")and say which method converts the string, which one validates it, and which one allocates the int. - Explain why an immutable subclass such as
intcannot validate in__init__and needs to do it in__new__. - Predict the exception from
PositiveInt(0)andPositiveInt("abc"), and where in the call chain each is raised. - Describe how a factory classmethod would move the string conversion off the caller while keeping subclasses working.
Mental model
For classes that inherit from int, str, or another immutable, __new__ is the only sensible place to reject bad input: the value is fixed at allocation, and __init__ runs later on an object that already carries it. Keep the order in mind (allocate first, then initialize) whenever you decide where validation belongs.
Mental model
read it top to bottom
PositiveInt("12")
↓ type.__call__ runs __new__(cls, "12")
conversion and validation happen here, before the object exists
↓ __new__ returns the finished instance
__init__ runs on that instance (the default one does nothing)
↓
number bound to the new int subclass instanceCore idea
Calling a class runs a two-stage protocol: __new__ receives the class plus the arguments and produces the object, usually by returning super().__new__(cls, ...); __init__ then receives that finished object to attach or check state. When the class is immutable, its value is set during allocation, so __new__ is where input becomes the stored value and where validation has to happen. Most classes only customize __init__; PositiveInt is the case that forces __new__.
__new__
__new__ creates and returns the new instance before __init__ initializes it. It matters most for immutable subclasses, custom allocation, and metaclass-driven construction.
__init__
__init__ configures an already-created instance and must return None. Validation can happen here when an invalid object should never finish initialization.
Instance creation
Instance creation defines how instances or runtime objects come into existence. Separate allocation, initialization, ownership, and validation because Python often exposes those stages through different hooks.
Initialization
Initialization is the second phase of construction: __init__ receives the instance that __new__ returned and configures it, usually by binding attributes. It runs once per successful call to the class and must return None, because its job is side effects on an existing object, not allocation. If __new__ returns something that is not an instance of the class, initialization is skipped.
Validation
Constructor validation prevents creation of objects that violate essential invariants. Raise a precise exception close to the invalid input rather than letting a corrupted object escape.
Factory methods preview
An alternate constructor is commonly a class method that converts another representation into an instance. It keeps construction policy on the class while preserving subclass behavior.
Walkthrough
class PositiveInt(int):subclasses a built-in immutable type, so each instance's numeric value is fixed at allocation time and cannot be adjusted afterward.__new__(cls, value)first coerces withvalue = int(value), so"12"becomes12;"abc"raisesValueErrorfromintitself, before any instance exists.- The guard
if value <= 0: raise ValueError(...)rejects zero and negatives, andsuper().__new__(cls, value)then allocates the int with that value; passingclskeeps the return type correct for subclasses. - Predict before running: what
print(number, type(number))shows, which line raises forPositiveInt(0), and whether__init__ever runs in this class.
Experiments to try
- Run
PositiveInt("12")andPositiveInt(12), then printtype(number).__mro__to confirm the instance is the subclass, not a plainint. - Call
PositiveInt(0)andPositiveInt("abc"); read both tracebacks and identify which exception comes from your guard and which fromint(value)inside__new__. - Add an
__init__(self, value)that prints"init ran"and observe when it fires relative to__new__; then explain whyPositiveIntdoes not need one. - Move the positivity check into
__init__instead and decide whether an invalid object can be created before the check runs.
Common mistakes
- Validating in
__init__for an immutable subclass: the value was already fixed by__new__, so the check cannot change what was allocated and the object can exist briefly in an invalid state. - Forgetting to return from
__new__: falling off the end returnsNone, Python skips__init__, and the caller receivesNoneinstead of an instance. - Returning a value other than
Nonefrom__init__: calling the class then raisesTypeError, because initialization is meant to mutate the object in place. - Assuming the conversion is exact:
PositiveInt(1.5)runsint(1.5), which truncates to1, so the guard sees a positive value and the fraction disappears silently.
Practice: Easy
- Run the worked example, then print
number + 3to confirm the instance behaves like anint. CreatePositiveInt("7")next and predict the result oftype(...)before running. - Call
PositiveInt(0)andPositiveInt(-3). Record the exactValueErrorand confirm that your guard rejected them, not the conversion. - Add an
__init__(self, value)toPositiveIntthat setsself.seen = value; runPositiveInt("12")and explain the order in which__new__and__init__ran.
Practice: Medium
- Add a
from_hex(cls, text)classmethod that parses withint(text, 16)and returnscls(value). Check thatPositiveInt.from_hex("ff")produces aPositiveIntand that subclassing the class still works. - Write a
Temperatureclass whose__init__rejects values below absolute zero, then decide whether the class needs__new__at all by checking whether its instances are mutable. - Build a class whose
__new__raises for non-integer input and whose__init__prints a message. Call it with bad and good input and record exactly which call skips__init__.
Practice: Hard
- Design an immutable
Ratioclass with two int fields fixed at allocation:__new__normalizes the sign and validates against a zero denominator. Define the tests, including type errors and division by zero, before implementing. - Build a failure lab around three constructor traps: an
__init__that returns a value, a__new__that forgets to return, and a positivity check placed in__init__of an immutable subclass. Show the exact error or wrong result each produces. - Connect this lesson to the method kinds lesson: move
PositiveInt's string parsing into a classmethod alternate constructor, then argue what a subclass inherits for free that hard-codedPositiveInt(...)calls would lose.
Lesson checklist
- I can state what
__new__decides and what__init__decides in one sentence each. - I can explain why
PositiveIntvalidates inside__new__rather than__init__. - I can predict which exception
PositiveInt(0)andPositiveInt("abc")raise and where each is raised. - I can describe what
super().__new__(cls, value)does with the class and the value.
Remember
Calling a class runs `__new__` first, which allocates and returns the instance, then `__init__`, which configures it and must return `None`. For an immutable subclass such as `PositiveInt`, the value is fixed during allocation, so that is where conversion and validation belong; for ordinary mutable classes, `__init__` usually does the whole job.
Interview angles
What is the main purpose of **__new__**?+
__new__ creates and returns the new instance before __init__ initializes it. It matters most for immutable subclasses, custom allocation, and metaclass-driven construction.
What should you pay attention to when using **__init__**?+
__init__ configures an already-created instance and must return None. Validation can happen here when an invalid object should never finish initialization.
How does **Instance creation** fit into this lesson?+
Instance creation defines how instances or runtime objects come into existence. Separate allocation, initialization, ownership, and validation because Python often exposes those stages through different hooks.
Why does an `__init__` that returns a value fail when the class is called?+
type.__call__ expects initialization to mutate the new object in place and return None; any other return value raises TypeError. Returning self from __init__ is therefore not a shortcut for chaining, and the fix is to keep the side effects and let the method fall through.