Lesson 8
Making Objects the Main Star!
Chapter 6: Object methods
Exercise
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.
Update your class definition for Car
to incorporate the four methods:
accelerate()
should take an input argumentrate
, and increment thespeed
attribute of the car by the givenrate
. The value ofrate
should default to1
if not given.decelerate()
should take an input argumentrate
, and decrement thespeed
attribute of the car by the givenrate
, up to a minimumspeed
of0
(speed
cannot be negative). The value ofrate
should default to1
if not given.brake()
should set thespeed
attribute of the car to0
.steer()
should take an input argumentangle
, and add theangle
to the currentrotation
attribute of the car. The minimum value forrotation
is-180
, and maximum180
. Sorotation
should be ‘clipped’ to-180
if it is lower than-180
, and clipped to180
if it is greater than180
.
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