Functions and Objects · Objects · lesson 8 of 10
Inheritance
about 15 minutes · free · runs in your browser
Building on another class
A class can start from an existing one and change only what differs:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
Dog inherits __init__ from Animal and overrides speak.
When a subclass needs its own __init__ as well, super() calls the parent's version
so you do not repeat its work:
class Cat(Animal):
def __init__(self, name, indoor):
super().__init__(name)
self.indoor = indoor
Inheritance is worth reaching for when the child genuinely is a kind of the parent. When you only want to reuse some code, a plain function or holding an instance as an attribute is usually the better tool.
Your turn: Shape is written for you. Add Circle and Rectangle, each with
its own area().
You start from this, and edit it in the browser:
class Shape:
def __init__(self, name):
self.name = name
def area(self):
return 0
class Circle(Shape):
def __init__(self, radius):
# Call super().__init__ with the name "circle", then store the radius.
pass
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
pass
def area(self):
pass