Learntofish's Blog

A blog about math, physics and computer science

Tutorial: Object Oriented Programming in Python – Part 5

Posted by Ed on December 10, 2011

This is the continuation of the Python OOP tutorial. Here, I will talk about inheritance. The general syntax is:

class DerivedClass(BaseClass)

Example:
Last time (in part 4) we wrote a Vehicle class that allowed us to create objects with the attribute speed and methods to change the speed. Suppose we wanted to create a motorcycle object that has additional attributes such as the width of its tires. Then we could write a completely new class Motorcycle or instead reuse the Vehicle class to build the Motorcycle class.

Copy the code below and save it the file vehicle.py from last time:

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.")

class Motorcycle(Vehicle):
    # additional attributes
    widthFrontTire = 95
    widthRearTire = 95

    def setWidthTires(self, front, rear):
        self.widthFrontTire = front
        self.widthRearTire = rear
        print("You have just put on some tires.")

    def printTireInfo(self):
        print("Width of front tire: ", self.widthFrontTire, " mm.")
        print("Width of rear tire: ", self.widthRearTire, " mm.")

– In lines 01-18 is the Vehicle class.
– In lines 22-34 is the Motorcycle class.
– Notice line 22: class Motorcycle(Vehicle) means that the Motorcycle class inherits everything from the Vehicle class. Or in other words: Everything from the Vehicle class is included in the Motorcycle class.
– In line 24 I declared the attribute widthFrontTire and initialized it with 95. The same is done with widthRearTire in line 25.
– In line 25 27 we have the method setWidthTires() to put other tires on our motorcycle.
– In line 32 the method printTireInfo() allows us to check the width of the tires.
You may ask why I declared and initialized the attributes widthFrontTire and widthRearTire in line 24 and 25. The reason is the printTireInfo() method. Without the initialization we get an error because printTireInfo() tries to access the attributes widthFrontTire and widthRearTire in lines 33 and 34.

Run the file vehicle.py in the Python-Shell (for example in IDLE by pressing F5). Then, go to the Python-Shell and type:

>>> m = Motorcycle(40, 120)
You have just created a vehicle.
>>> m.status()
The speed of the vehicle is 40 km/h.
>>> m.setWidthTires(90, 100)
You have just put on some tires.
>>> m.printTireInfo()
Width of front tire:  90  mm.
Width of rear tire:  100  mm.

– In line 1 we create a Motorcycle object with the properties 40 km/h as the current speed and 120 km/h as the maximum speed.
– In line 3 we check the speed of the motorcycle with the status() method.
Now, if you look closely at the Motorcycle class, we do not see a status() method. Why can we use it? The reason is the way we have built Motorcycle. Motorcycle inherits everything from Vehicle, including the status() method.
– In line 5 we use the method setWidthTires() that is not present in the Vehicle class, but which we included in the Motorcycle class. The same goes for the printTireInfo() method in line 7.

In summary: Inheritance is a way to reuse attributes and methods from a base class to build a derived class. The general syntax is

class DerivedClass(BaseClass)

as mentioned in the beginning.

Exercise 1:
1a) Create a motorcycle with current speed 0 km/h and maximum speed 70 km/h.
1b) Increase the speed by 50 km/h and check the speed with status().
1c) Increase the speed by 30 km/h and check the speed with status().
1d) Decrease the speed by 80 km/h and check the speed with status().
1e) Print the width of the tires. What is their initial size?
1f) Change the width of the tires to 92 mm and 108 mm respectively for the front and rear and check if the change has been done correctly.

Exercise 2:
2a) Write a class Automobile that inherits from Vehicle.
Add the attributes gear and color to it. Initialize them properly.
2b) Write a method setGear() that allows assigning a value to the attribute gear.
2c) Include a method status() that prints the speed and gear of the automobile.
2d) Write a method setColor() that lets you assign a value to the attribute color.
2e) Write a method getColor() that returns the color. Note that returning is not the same as printing, see here.
2f) Create an Automobile object with 0 km/h as current speed and 150 km/h as maximum speed.
2g) Increase the speed by 40 km/h and set the gear to 2. Then use status().
2h) Set the color of the automobile to red.
2i) Save the color of the automobile in a variable myColor. Then check the color by using print(myColor).

Solution to Exercise 1:

>>> m = Motorcycle(0, 70)
You have just created a vehicle.
>>> m.accelerate(50)
>>> m.status()
The speed of the vehicle is 50 km/h.
>>> m.accelerate(30)
>>> m.status()
The speed of the vehicle is 70 km/h.
>>> m.brake(80)
>>> m.status()
The speed of the vehicle is 0 km/h.
>>> m.printTireInfo()
Width of front tire:  95  mm.
Width of rear tire:  95  mm.
>>> m.setWidthTires(92, 108)
You have just put on some tires.
>>> m.printTireInfo()
Width of front tire:  92  mm.
Width of rear tire:  108  mm.

Solution to Exercise 2:
The Automobile class can just be saved in the file vehicle.py together with the classes Vehicle and Motorcycle.

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.")

class Motorcycle(Vehicle):
    # additional attributes
    widthFrontTire = 95
    widthRearTire = 95

    def setWidthTires(self, front, rear):
        self.widthFrontTire = front
        self.widthRearTire = rear
        print("You have just put on some tires.")

    def printTireInfo(self):
        print("Width of front tire: ", self.widthFrontTire, " mm.")
        print("Width of rear tire: ", self.widthRearTire, " mm.")

class Automobile(Vehicle):
    # additional attributes
    gear = 0
    color = "blue"

    def setGear(self, gear):
        self.gear = gear

    def status(self):
        print("The speed of the vehicle is", self.speed, "km/h.")
        print("You have switched to gear", self.gear, end=".")

    def setColor(self, color):
        self.color = color

    def getColor(self):
        return self.color

Answers:
2a) Inhertiance and new attributes: line 38-41
2b) Method setGear(): line 43-44
2c) Method status(): line 46-48
2d) Method setColor(): line 50-51
2e) Method getColor(): line 53-54
2f)-2i) See Python-Shell below:

>>> a = Automobile(0, 150)
You have just created a vehicle.
>>> a.accelerate(40)
>>> a.setGear(2)
>>> a.status()
The speed of the vehicle is 40 km/h.
You have switched to gear 2.
>>> a.setColor("red")
>>> myColor = a.getColor()
>>> print(myColor)
red

Note that I have written a method status() in the class Motorcycle Automobile although there was already such a method in Vehicle. We call this overwriting a method since we overwrite the original method in the base class.

Advertisements

3 Responses to “Tutorial: Object Oriented Programming in Python – Part 5”

  1. Seems to me…

    Text: In line 25 we have the method setWidthTires() to put other tires on our motorcycle.
    Suggested change: In line 27….

    Text: Note that I have written a method status() in the class Motorcycle….
    Suggested change: Note that I have written a method status() in the class Automobile….

    Thanks. This series has been very helpful.

  2. I believe that with respect to your final sentence on this page, what you are explaining is more commonly referred to as ‘overriding the method’, rather that ‘overwriting the method’. It is overriding the behaviour of the original method but it not destroying it in any way. Please correct me if I am wrong, though because I am rather inexperienced in OOP.

    I’m really enjoying this tutorial. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: