Chapter 6: Object methods

Exercise

face Josiah Wang

Practice time!

Let’s extend our previous exercise on designing a Car object to incorporate methods.

Suppose that your passionate software analyst has now added methods to Car. Here is the updated class diagram.

Class diagram for car

Update your class definition for Car to incorporate the four methods:

  • accelerate() should take an input argument rate, and increment the speed attribute of the car by the given rate. The value of rate should default to 1 if not given.
  • decelerate() should take an input argument rate, and decrement the speed attribute of the car by the given rate, up to a minimum speed of 0 (speed cannot be negative). The value of rate should default to 1 if not given.
  • brake() should set the speed attribute of the car to 0.
  • steer() should take an input argument angle, and add the angle to the current rotation attribute of the car. The minimum value for rotation is -180, and maximum 180. So rotation should be ‘clipped’ to -180 if it is lower than -180, and clipped to 180 if it is greater than 180.

Remember that the first parameter should always be self! I will not explicitly mention this in my instructions, but you should assume that you expect self to be there!

Sample usage

>>> my_car = Car("Audi A6", 2018, True, 6)
>>> my_car.accelerate()
>>> print(my_car.speed)
1.0
>>> my_car.accelerate(5)
>>> print(my_car.speed)
6.0
>>> my_car.decelerate()
>>> print(my_car.speed)
5.0
>>> my_car.decelerate(20)
>>> print(my_car.speed)
0.0
>>> my_car.accelerate(10)
>>> print(my_car.speed)
10.0
>>> my_car.brake()
>>> print(my_car.speed)
0.0
>>> my_car.steer(30)
>>> print(my_car.rotation)
30.0
>>> my_car.steer(200)
>>> print(my_car.rotation)
180.0
>>> my_car.steer(-200)
>>> print(my_car.rotation)
-20.0
>>> my_car.steer(-200)
>>> print(my_car.rotation)
-180.0