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.
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
- Initialise every attribute.
- Validate and raise early.
- Use None for mutable defaults.
Code examples
Construction order
__new__ creates the object __init__ sets it up with 42 42
Validating arguments
Pen rejected: price can't be negative
More examples
Defaults and an alternative constructor
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:
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
Prefer
__init__ must return None; returning anything else raises TypeError.
Creating attributes outside __init__ only
Avoid
Prefer
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
- 1Write a Date class with __init__(day, month, year) that validates its arguments and a from_string('27/11/2026') constructor.
- 2Give 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?