Overview
Build specialised classes on top of general ones: inherit behaviour, override what's different, and reuse the parent with super().
- class Child(Parent)
- Overriding methods
- super().__init__(...)
- isinstance() with subclasses
Short Course
A subclass gets every method of its parent. Override the ones that differ,
and call the parent's version with super().
class Animal:
sound = "..."
def speak(self):
return f"{type(self).__name__} says {self.sound}"
class Dog(Animal):
sound = "Woof"
Dog().speak() # 'Dog says Woof'
Task
Shape is done. Write Rectangle(width, height) with an area() method,
and Square(side) as a subclass of Rectangle that reuses it through
super().__init__. Give each class its own name.
Test Suites
Pending
Stdout