Lesson 9
No Object is an Island
Chapter 2: Object interaction
Aggregation exercise
Let’s try to apply what we have just discussed to our Car
from earlier.
For this exercise, let us add some Wheel
s to our car.
Your beloved software analyst now wants to be able to influence the acceleration and deceleration speed of a car based on the resistance from its wheels.
Your task
Implement the Wheel
class as depicted in the diagram. This should be quite straightforward!
Then update your Car
class to take in a list of wheels
as an input argument to the Car
constructor. You are expecting wheels
to be a list of Wheel
instances.
Now, update the accelerate()
and decelerate()
methods to reduce the given rate
by a certain amount depending on the number of wheels and each wheel’s resistance. Use the formula rate^\prime = rate - 0.5 \times \sum_{i}^{wheels} resistance_{i}, where resistance_{i} is the resistance from wheel i. Apologies to all engineers out there for this horrible equation - I am clearly not an automotive engineer or a physicist!
For example, if rate=5
, and your car has four wheels each with resistance value 0.5
, the new rate should be 5 - 0.5 * (4*0.5)
, which is 4
. Therefore, if car.accelerate(5)
is invoked, then car.speed
should increase by 4
. Similarly, if car.decelerate(5)
is invoked, then car.speed
should decrease by 4
. Remember that car.speed
should not be less than 0!
Sample usage
>>> wheels = [Wheel(38, 0.5)] * 4 # 4 wheels with diameter 38 and resistance 0.5
>>> my_car = Car("Honda Civic", 2015, True, wheels)
>>> my_car.accelerate(20)
>>> print(my_car.speed)
19.0
>>> my_car.decelerate(10)
>>> print(my_car.speed)
10.0
>>> my_car.brake()
>>> print(my_car.speed)
0.0