Python 3D Academyবাংলা

Inheritance: building on a class

🌍 In real life. A bus, a car and a motorbike are all vehicles. Every vehicle has wheels and can move. A bus also has many seats; a motorbike also has a kickstand. Nobody describes "has wheels, can move" all over again for each one; you say "a bus is a vehicle, plus…".

Python does the same with inheritance:

  • class Bus(Vehicle): makes a new class that inherits everything from Vehicle
  • Vehicle is the parent (or base) class
  • Bus is the child (or subclass), and it can add its own extras

The idea in one sentence: class Child(Parent): makes a new class that inherits every attribute and method of the parent, and can add its own.

Its words:

  • inheritance: a child class getting everything from a parent class
  • parent (base class) and child (subclass)
  • is-a: inheritance fits when "a Bus is a Vehicle" is true
class Vehicle:
    def __init__(self, wheels):
        self.wheels = wheels

    def describe(self):
        return "A vehicle with " + str(self.wheels) + " wheels"

class Bus(Vehicle):
    def seats_message(self):
        return "Room for lots of people!"

b = Bus(6)
print(b.describe())
print(b.seats_message())
Bus has no __init__ or describe of its own: it uses Vehicle's.

How does rex.describe() work when Dog never wrote describe? When Python looks up a name, it climbs a tower:

  1. the object itself
  2. its class (Dog)
  3. the parent class (Animal)

The first floor that has the name wins. If no floor has it, you get an AttributeError. Watch:

class Animal:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return self.name + " is an animal"

    def eat(self):
        return self.name + " is eating"

class Dog(Animal):
    def fetch(self):
        return self.name + " fetches the ball!"

rex = Dog("Rex")
print(rex.describe())
print(rex.eat())
print(rex.fetch())

Why inherit? Code shared by several classes is written once, in the parent. Fix a bug in Vehicle.move, and every bus, car and bike is fixed. Looking up an inherited method costs one extra floor of the lookup tower, which is tiny.

Mistakes and edge cases.

  • Forgetting the brackets. class Bus: (without (Vehicle)) inherits nothing, so bus.move() gives an AttributeError.
  • A name that's on no floor. If neither the object, its class nor any parent has it, you get AttributeError: 'Dog' object has no attribute ....
  • Inheriting for code reuse alone. If "child is a parent" isn't true, inheritance makes confusing code; Lesson 22.4 shows the alternative.

Quiz

  1. What does this print?

    class Animal:
        def __init__(self, name):
            self.name = name
    
        def hello(self):
            return "Hi, I'm " + self.name
    
    class Cat(Animal):
        pass
    
    print(Cat("Tom").hello())
  2. In class Bus(Vehicle):, which is the parent class?

    • Vehicle
    • Bus
    • Both
  3. What does this print?

    class Shape:
        sides = 0
    
    class Triangle(Shape):
        sides = 3
    
    class Blob(Shape):
        pass
    
    print(Triangle().sides, Blob().sides)
  4. Python looks up rex.fetch. In what order does it search?

    • rex itself, then Dog, then Animal
    • Animal, then Dog, then rex
    • Only in Dog
  5. Which line has a mistake?

    class Animal:
        def __init__(self, name):
            self.name = name
    
    class Dog(Animal):
        def fetch(self):
            return self.name + " fetches!"
    
    print(Dog().fetch())

Coding tasks

  1. Animal is written for you. Write a class Dog that inherits from it and adds a method fetch() returning "<name> fetches!".

  2. Person is written for you. Write Teacher, a kind of Person, with a method teach(subject) returning "<name> teaches <subject>".