Tracing a vehicle built from parts and subclasses

The Python classes below combine inheritance and composition. A Vehicle holds an engine object and delegates part of its speed calculation to it.


Python
class Engine:
    def __init__(self, power):
        self.power = power

    def output(self):
        return self.power * 10

class TurboEngine(Engine):
    def output(self):
        return super().output() * 2

class Vehicle:
    def __init__(self, engine):
        self.engine = engine

    def speed(self):
        return self.engine.output() + self.bonus()

    def bonus(self):
        return 5

class Truck(Vehicle):
    def bonus(self):
        return -20

v = Vehicle(Engine(6))
print(v.speed())                    # Print 1

t = Truck(Engine(6))
print(t.speed())                    # Print 2

print(Truck(TurboEngine(5)).speed())  # Print 3

r = Truck(Engine(4))
r.engine = TurboEngine(4)
print(r.speed())                    # Print 4


Give the value shown by each of the four print calls as a whole number.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Composition, Inheritance Questions: