alphaPlan · Data Structures, Algorithms & the Web · Cheat-sheet 05
Object-oriented programming
Describe the things in your program as classes, build objects from them, and let them share, guard and vary their behaviour.
Ideas to remember
- 01A class is a blueprint and an object is one thing built from it; each object carries its own data, so changing one leaves the others alone.
- 02Attributes are the data an object carries and methods are the actions it can take; self always means this particular object.
- 03An instance attribute is set in __init__ and belongs to one object; a class attribute is written in the class body and shared by all.
- 04A child class names its parent in parentheses and inherits its attributes and methods; a method with the same name in the child overrides the parent's.
- 05Polymorphism lets one loop call the same method name on a mixed pile of objects and let each answer in its own way.
- 06Encapsulation hides data behind guarded methods, and an abstract base class states what every child must provide without saying how.
Words
- def __init__(self, title, pages):
- Runs automatically whenever a new object is created and sets up its starting data.
- self.balance
- The balance of this account, not some global number.
- class Bus(Vehicle):
- Bus inherits everything Vehicle has and adds or replaces only what is different.
- super().__init__(make, wheels)
- Runs the parent's __init__ first, so the child reuses its setup instead of copying it.
- self.__balance
- A double leading underscore makes the attribute private, so code outside the class cannot reach it by the obvious path.
- @abstractmethod
- Marks a method with no body that every child must supply; a bare base class marked this way cannot be created at all.
Do this
- Read self as the specific object this is running on.
- Go through a method like deposit instead of setting balance by hand, so the guard inside it can refuse bad input.
- Use inheritance only when you can honestly say a child is a kind of parent; a wheel is a part of a car, not a child.
- Give every shape class the same method name, area, so one loop handles them all and a new kind fits without touching the loop.
- Do not force classes on a five line script; their value shows when several things each carry state and behaviour.
Watch out
- A single underscore like _balance is only a polite sign; Python enforces privacy only for the double underscore __balance.
- Changing a class attribute such as interest_rate changes it for every object at once, so use it only for values that are the same for the whole kind.
- Reading card.__balance from outside raises an AttributeError; that failure is the encapsulation working.
Found something unclear, outdated or improvable? Suggest an improvement