Step 1 of 8 · Reading · ~3 min
Learn
Object-Oriented Programming
Classes and Objects
You will be able to design a class that protects its data: it validates on creation, computes values on demand and shares some state.
So far a record was a dict or tuple and the functions guarding it lived elsewhere; a class keeps data and rules together. class X(Exception): pass from raising-exceptions was already one, with no body.
Methods receive the instance
A method is a function in a class body; the object before the dot becomes its first argument, self.
Class attributes versus instance attributes
A name assigned in the class body is shared; one assigned on self belongs to one object. This is the mutable-default trap from arguments-and-scope again:
The fix is self.members = [] in __init__. A second trap: self.x += 1 reads the class value but writes a new instance attribute:
To update shared state, name the class: Ticket.issued += 1.
Alternative constructors and utilities
@classmethod receives the class as cls; it is the home of alternative constructors. @staticmethod receives nothing extra: a plain function filed in the class. Here @ is only syntax; function-decorators explains it.
Invariants: validate, and order the side effects
An invariant is a fact that must always hold, like "never below absolute zero". Check it in __init__ and raise ValueError; no object is returned, but statements before the raise already ran:
Validate first, then change state.
Properties
@property makes a method read like an attribute. Without a setter it is read-only and recomputed on each access, so it cannot go stale. @name.setter validates every assignment, including the one in __init__:
Privacy is a convention
_name means "internal". __name is renamed to _ClassName__name; that avoids clashes in subclasses and is not security.
Objects are references
== on instances is identity until special-methods changes it; is asks whether two names point at one object:
Common mistakes
- A list in the class body (
guests = []): a guest booked into one room shows up in every room. - Counting before validating:
countreports 1 where 0 rooms exist. self.count += 1as a shared counter: the class total stays 0.- Storing free seats in
__init__: correct until the first booking, then stale. Compute it in a property.
Your exercise
Build the booking system around a Room class: shared counter, parse constructor, computed free. The usual slip is counting a room before its capacity is validated.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…