Chapter 2: Object interaction

Dependency exercise

face Josiah Wang

Here is a (hopefully) quick exercise to help you get a feel of what we just discussed.

Following on from the Car class you created in our exercise from Lesson 8, your software analyst has now decided that you will need a Driver to drive the cars, since different drivers might drive a car differently. Here is the updated class diagram.

Class diagram for Driver and Car

Note that the arrow in this diagram indicates that the dependency relationship goes one way. So a Driver can use a Car instance, while a Car does not even know that a Driver exists!

Your task

Implement the Driver class as depicted in the diagram. For the drive() method, start by printing "Driver {name} is driving a {car_model}.". Then you can implement the ‘driving’ bit however you like, as long as at least one of the methods of Car is called (e.g. accelerate(), decelerate(), brake(), steer()). You can copy these from your previous test cases or examples. End the method with "Driver {name} has finished driving."

To test your class, create a new Car instance, and then create a new Driver instance. Then get your Driver instance to drive the car you just created!

Sample usage

>>> sports_car = Car("Porsche GT2", 2006, True, 4)
>>> driver = Driver("F123", "Michael Schumacher")
>>> driver.drive(sports_car)
Driver Michael Schumacher is driving a Porsche GT2.
Driver Michael Schumacher is accelerating the car.
The car's speed is now 20.0.
Driver Michael Schumacher is steering the car.
The car's rotation is now 90.0.
Driver Michael Schumacher is braking the car.
The car's speed is now 0.0.
Driver Michael Schumacher has finished driving.
>>>