Tutorial: Object Oriented Programming in Python – Part 4
Posted by Ed on December 9, 2011
This is the continuation of the Python OOP tutorial. Today I describe how to change an attribute in a simple Vehicle class:
class Vehicle: def __init__(self, speed): self.speed = speed print("You have just created a vehicle.") def accelerate(self,x): self.speed = self.speed + x def brake(self,x): self.speed = self.speed - x def status(self): print("The speed of the vehicle is", self.speed, end=" km/h.")
Save the code in a file vehicle.py and run it (e.g. in IDLE by pressing F5).
>>> v = Vehicle(50) You have just created a vehicle. >>> v.status() The speed of the vehicle is 50 km/h. >>> v.accelerate(20) >>> v.status() The speed of the vehicle is 70 km/h. >>> v.brake(40) >>> v.status() The speed of the vehicle is 30 km/h.
Exercise:
a) The class has a flaw. If you type v.brake(40) once again the speed will be -10 km/h. Change the class in such a way that the speed cannot become negative after braking.
b) Another flaw is the missing maximum speed. Introduce an attribute maxSpeed in the __init__() method. Ensure that the maximum speed cannot be exceeded.
c) Test your new class with the following commands in the Python-Shell:
v = Vehicle(50, 200) # where 200 is the maximum speed v.status() v.accelerate(120) v.status() v.accelerate(100) v.status() v.break(80) v.status() v.break(70) v.status() v.break(60) v.status()
Solution:
class Vehicle: def __init__(self, speed, maxSpeed): self.speed = speed self.maxSpeed = maxSpeed print("You have just created a vehicle.") def accelerate(self,x): self.speed = self.speed + x if(self.speed > self.maxSpeed): self.speed = self.maxSpeed def brake(self,x): self.speed = self.speed - x if(self.speed < 0): self.speed = 0 def status(self): print("The speed of the vehicle is", self.speed, end=" km/h.")
In order to prevent the wrong velocities I included two if statements. Save the code in a file vehicle.py and run it (e.g. in IDLE by pressing F5).
>>> v = Vehicle(50,200) You have just created a vehicle. >>> v.status() The speed of the vehicle is 50 km/h. >>> v.accelerate(120) >>> v.status() The speed of the vehicle is 170 km/h. >>> v.accelerate(100) >>> v.status() The speed of the vehicle is 200 km/h. >>> v.brake(80) >>> v.status() The speed of the vehicle is 120 km/h. >>> v.brake(70) >>> v.status() The speed of the vehicle is 50 km/h. >>> v.brake(60) >>> v.status() The speed of the vehicle is 0 km/h. >>>
Leave a comment