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

Chapter 3: Classes and attributes

Exercise

face Josiah

Ok, hopefully that was not too much information overload!

Perhaps we should try a quick exercise to see whether you really understood what we discussed.

Try to write your code from scratch without copying and pasting the code from the previous page. In fact, try your best to recall without even looking at the previous code! This will really help drill all these new concepts into your memory!

Suppose you need to design a software for a car dealer, or design a racing game, or some computer vision system to detect cars that enter a car park. So you will need to define a class for Car, since that is an object that you will need to represent! For simplicity, suppose that you are given the class diagram for Car below by your software analyst.

Class diagram for car

A Car instance should have six attributes: model, year, is_manual (whether the car has manual transmission), max_passengers (the maximum passenger capacity), speed (the current speed of the car), and rotation (the current angle of the steering wheel).

Programmers are not allowed to customise the speed and rotation attribute when creating the Car instance - both should automatically be set to 0 initially.

All other attributes are required in the constructor, except max_passengers where the default value should be set to 5 if not given.

With these constraints in mind, your task is to write a class definition for the class Car.

Sample instantiation

>>> dream_car = Car("Audi A6", 2018, True, 6)
>>> print(dream_car)
<__main__.Car object at 0x7fe1b958d820>
>>> print(isinstance(dream_car, Car))
>>> print(dream_car.model)
Audi A6
>>> print(dream_car.year)
2018
>>> print(dream_car.is_manual)
True
>>> print(dream_car.max_passengers)
6
>>> print(dream_car.speed)
0.
>>> print(dream_car.rotation)
0.
>>> personal_car = Car("Honda Civic", 2015, False)
>>> print(personal_car)
<__main__.Car object at 0x7fe1b958d820>
>>> print(personal_car.model)
Honda Civic
>>> print(personal_car.year)
2015
>>> print(personal_car.is_manual)
False
>>> print(personal_car.max_passengers)
5
>>> print(personal_car.speed)
0.
>>> print(personal_car.rotation)
0.