PCAP study materials
PCAP study resources

PCAP: Object-Oriented Programming

PCAP · Work through your exam, one topic at a time.

All guide sections

Object-Oriented Programming

Object-Oriented Programming

Candidates must understand classes, instances, __init__, self, instance versus class attributes, and the method resolution order (MRO) for inheritance. Instance attributes live in obj.__dict__; class attributes are shared and shadowed by instance attributes of the same name. Methods are functions defined in the class; self is passed automatically on instance calls.

Key concepts: @classmethod (receives cls), @staticmethod (receives nothing extra), @property (getter/setter/deleter), dunder methods (__str__ vs __repr__, __eq__, __len__, __iter__), and super() for cooperative inheritance. Name mangling turns __x into _Class__x (single underscore is only a convention). isinstance respects inheritance; type(x) is C does not.

Traps: mutable class attributes shared across instances (e.g., a class-level list appended to by every instance). Confusing __str__ (readable, used by print) with __repr__ (unambiguous, used in containers). Forgetting that defining __eq__ without __hash__ makes instances unhashable. Multiple inheritance follows C3 linearization-predict the MRO carefully. Overriding without calling super().__init__ skips parent setup. Also note private-by-convention attributes are still accessible.

Worked example: if class A: items = [], then a1 = A(); a1.items.append(1); a2 = A(); print(a2.items) prints [1], because both share the class list. Rule of thumb: put mutable defaults in __init__, not at class level.