Python Constructors
PCAP objective 4.6 is construct and initialize objects. __init__ runs automatically when an instance is created, receives the instance as self, and has two rules that are examined directly: the arguments must match like any function's, and it may not return anything but None. The mutable-default trap from the functions track reappears here in its most damaging form.
Object-Oriented Python Guide 13 of 25 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 15 min
__init__ is unchanged in Python 3. __new__ also exists and runs before it; neither exam examines __new__, and you will not need it.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the construction objective. This matters because __init__ may not return a value, and a mutable default inside one is shared by every object the class ever makes.
- seeing
__init__run when the object is created, never called directly - matching the arguments, and finding that
__init__may not return a value - writing a class with no
__init__at all - meeting the mutable default in its worst form, and the fix
- calling a parent constructor
Before you start
- guide 12 - you need an instance to initialise.
- guide 19 -
__init__is a function and follows every argument rule.
-
__init__ runs when the object is created
-
The arguments must match
-
__init__ may not return a value
-
A class with no __init__ at all
-
The mutable default, in its worst form
-
The fix
-
Calling a parent constructor
-
What the exam does with this objective