This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Inheritance

Battle cars!

face Josiah Wang

Quick inheritance exercise! Suppose your overly eager software analyst from the previous lesson now decided to enhance your racing car game with special cars that can do battle with other cars. Here is a new BattleCar class added to the mix.

Class diagram for BattleCar

Your task

BattleCar is like any other Cars, but has an additional method attack() that allows it to attack another car. When the .attack(another_car) method is invoked, the BattleCar instance will forcefully decelerate another_car by a rate corresponding to the BattleCar‘s strength attribute. The target of the attack can be any Car (does not have to be a BattleCar).

Your task is to implement this BattleCar class (the constructor and attack() method) as described above. Obviously, BattleCar should inherit from Car, and you should not reimplement any of Car‘s methods unnecessarily (do not repeat yourself!)

This should be a quick exercise. You should be able to implement the attack() method in one single line.

Sample usage

The following output assumes you are using the latest version of Car with resistance from Wheels from the last lesson.

>>> wheels = [Wheel(38, 0.5)] * 4  # 4 wheels with diameter 38 and resistance 0.5
>>> battle_car = BattleCar("The Terminator", 2020, True, wheels, strength=5)
>>> opponent_car = Car("Honda Civic", 2015, True, wheels)
>>> opponent_car.accelerate(50)
>>> print(opponent_car.speed)
49.0
>>> battle_car.accelerate(40)
>>> print(battle_car.speed)
39.0
>>> battle_car.attack(opponent_car)
>>> print(opponent_car.speed)
45.0