bhylu.com

Advertisements

__init__ Method

__init__ initialises an instance after it has been created. Use it to establish valid state before callers start using the object's methods.

Understand the idea

The constructor call supplies arguments that reach __init__ along with self. Validate assumptions that should hold for every instance. __init__ must return None; it is not the place to return an alternative object. For a compact data container, a dataclass can generate ordinary initialization work, but validation still needs a deliberate policy.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Booking:
    def __init__(self, seats):
        if seats <= 0:
            raise ValueError("Seats must be positive")
        self.seats = seats

print(Booking(2).seats)

Read the result

The valid instance stores 2. Passing zero or a negative value raises the stated ValueError.

Try one change

Test a negative count and decide whether Boolean or fractional seat values should also be rejected.