Inheritance & encapsulation
HandoutBuild on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.)
Click Run to see the output here.
The class Shape is given (its area returns 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side.
Click Run to see the output here.
Classes Dog and Cat are given, each with a speak(). Write speak_all(animals) that returns a list of each animal's speak() result, in order.
Click Run to see the output here.
Write a class Account whose __init__(self) sets a private balance self._balance to 0. Add deposit(self, amount) to add to it, and balance(self) to return it. Other code should use these methods, not touch _balance directly.
Click Run to see the output here.