Computer Science · Cheatsheet
Topic 7 · Object-Oriented Programming (HL)
Chapter 2 · Going deeper & exam practice
📋 Reference · always available
Encapsulation
Bundle data + methods together. HIDE internals (private attributes) + expose CONTROLLED interface (public methods).
Private (Python)
Single underscore `_x` = convention. Double underscore `__x` = name-mangled (effectively private).
Accessor (getter)
Method that RETURNS a private attribute's value. Read-only access.
Mutator (setter)
Method that SETS a private attribute, usually with VALIDATION (e.g. reject negative balance).
Data integrity
Encapsulation benefit — validation in setters prevents invalid states.
Implementation hiding
Can change internals (e.g. data structure used) WITHOUT breaking external code that uses the public interface.
Composition (has-a)
Object CONTAINS another as an attribute. `Car has-a Engine`. Flexible, replaceable.
Inheritance (is-a)
Subclass IS A kind of superclass. `Dog is-a Animal`. Use only when relationship is genuinely is-a.
Rule of thumb
Prefer COMPOSITION over INHERITANCE unless IS-A is genuinely true. Composition is more flexible.
Abstraction
Expose simple INTERFACE; hide complex implementation. Lets multiple implementations satisfy same interface.
Open-Closed Principle
Code should be OPEN for extension (new subclasses) but CLOSED for modification (existing code unchanged). Polymorphism enables it.
Common exam trap
Confusing override (same name, replaces parent) with overload (same name, different parameters — NOT supported by Python directly).