Skip to content

Module 11 · Object-Oriented Programming — topic 6 of 25

Constructors

How objects are created: __new__ and __init__, initialising state, validating constructor arguments, default values, and alternative constructors with class methods.

Beginner 10 min read·Lesson 163 of 306 in Python Programming

Learning objectives

  • Write constructors that fully initialise an object
  • Validate constructor arguments
  • Provide alternative constructors

Definition

A constructor is the code that runs when an object is created. In Python, calling a class first runs __new__ to create the instance and then __init__ to initialise it; __init__ is what you normally write.

Introduction

Product("Pen", 20) builds and sets up a product in one step. The constructor's job is to make sure every new object starts in a valid, complete state.

Why it matters

Objects that are half-initialised or invalid cause errors far away from where they were created. Constructors are the single place to prevent that.

Detailed explanation

Calling a class runs __new__ (which creates the empty object; you rarely override it) and then __init__(self, ...) with the same arguments.

__init__ should set every attribute the object needs, so other methods can rely on them existing.

Validation belongs in the constructor: raise ValueError or TypeError for invalid arguments, so no invalid object can ever exist.

Default parameter values make arguments optional; the same mutable-default warning applies — use None and create the list inside.

A class can offer alternative constructors as class methods, e.g. Date.from_string("2026-11-27"), which parse input and then call the normal constructor (see Class methods).

A good constructor leaves the object complete and valid: after it returns, every attribute exists and every rule of the class already holds, so no later method has to check whether setup happened.

Syntax

Python
class Product:
def __init__(self, name, price, tags=None):
if price < 0:
raise ValueError("price can't be negative")
self.name = name
self.price = price
self.tags = tags if tags is not None else []
  • Initialise every attribute.
  • Validate and raise early.
  • Use None for mutable defaults.

Code examples

Construction order

Python
class Demo:
def __new__(cls, *args):
print("__new__ creates the object")
return super().__new__(cls)
def __init__(self, value):
print("__init__ sets it up with", value)
self.value = value
d = Demo(42)
print(d.value)
Output
__new__ creates the object
__init__ sets it up with 42
42

Validating arguments

Python
class Product:
def __init__(self, name, price):
if not name.strip():
raise ValueError("name is required")
if price < 0:
raise ValueError("price can't be negative")
self.name = name.strip()
self.price = price
print(Product(" Pen ", 20).name)
try:
Product("Bag", -5)
except ValueError as e:
print("rejected:", e)
Output
Pen
rejected: price can't be negative

More examples

Defaults and an alternative constructor

Python
class Temperature:
def __init__(self, celsius=0.0):
if celsius < -273.15:
raise ValueError(f"{celsius} C is below absolute zero")
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, f):
return cls(round((f - 32) * 5 / 9, 2))
@classmethod
def parse(cls, text):
value, unit = float(text[:-1]), text[-1].upper()
return cls.from_fahrenheit(value) if unit == "F" else cls(value)
for t in [Temperature(), Temperature(37), Temperature.from_fahrenheit(212), Temperature.parse("98.6F"), Temperature.parse("-40C")]:
print(t.celsius)
Output
0.0
37
100.0
37.0
-40.0

Step-by-step explanation

  • Temperature() uses the default 0.0.
  • from_fahrenheit converts and then calls cls(...), so validation in __init__ still runs.
  • parse reads text like '98.6F' and chooses the right constructor.
  • Every path creates a fully initialised, validated object.

Expected output

Running “Defaults and an alternative constructor” prints exactly:

TextOutput
0.0
37
100.0
37.0
-40.0

Practical applications

  • datetime.fromisoformat and dict.fromkeys are alternative constructors.
  • ORM models validate fields when objects are created.

Best practices

  • Make the constructor leave the object valid and complete.
  • Validate early with clear error messages.
  • Offer class-method constructors for other input formats.

Common mistakes

Returning a value from __init__

Avoid

def __init__(self, x):
self.x = x
return self

Prefer

def __init__(self, x):
self.x = x

__init__ must return None; returning anything else raises TypeError.

Creating attributes outside __init__ only

Avoid

def load(self):
self.data = ... # other methods crash if load wasn't called

Prefer

def __init__(self):
self.data = None

Initialise every attribute in __init__ so it always exists.

Important notes

  • Override __new__ only for special cases such as immutable types or singletons.

Key takeaways

  • Creating an object runs __new__ then __init__.
  • __init__ initialises and validates the object.
  • Class methods can provide alternative constructors.

Try it yourself

  1. 1
    Write a Date class with __init__(day, month, year) that validates its arguments and a from_string('27/11/2026') constructor.
  2. 2
    Give a Playlist class an optional list of songs, avoiding the mutable default trap.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module