Object-oriented programming · 7 / 26 Theory

Polymorphism and class diagrams

Polymorphism means "many forms": objects of different classes respond to the same message (the same method), each in its own way.

An example

class Vehicle:
    def move(self):
        print("The vehicle moves")

class Car(Vehicle):
    def move(self):
        print("The car rolls down the road")

class Boat(Vehicle):
    def move(self):
        print("The boat sails")

class Plane(Vehicle):
    def move(self):
        print("The plane flies")

fleet = [Car(), Boat(), Plane()]
for v in fleet:
    v.move()      # each one does its own thing
# The car rolls down the road
# The boat sails
# The plane flies

Whoever goes through the list does not need to know which class each object belongs to: only that all of them have move(). If tomorrow Bicycle is added, the loop keeps working unchanged. That is the big advantage: code that works with the superclass and adapts to any subclass.

Polymorphism with calculations: shapes

import math

class Shape:
    def area(self):
        return 0

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return math.pi * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    def area(self):
        return self.base * self.height

shapes = [Circle(1), Rectangle(2, 3)]
for s in shapes:
    print(round(s.area(), 2))   # 3.14  and  6

Duck typing

In Python the classes do not even need to be related: it is enough for the object to have the method being invoked. "If it walks like a duck and quacks like a duck, it is a duck":

class Duck:
    def speak(self):
        print("Quack")

class Robot:
    def speak(self):
        print("Beep beep")

for x in [Duck(), Robot()]:
    x.speak()

Reading a class diagram

Class diagrams (UML) are the standard way to draw a set of classes before programming them. Each class is a rectangle with three zones: name, attributes and methods.

SymbolMeaningIn Python
+Publicself.name
#Protectedself._name
-Privateself.__name
Arrow with an empty triangleInheritance (the arrow goes from the subclass to the superclass)class Child(Parent):

For example, this diagram:

Vehicle                  Car
---------------          ---------------
- brand: str             - doors: int
+ move()           ◄──── + move()

# translates into:
class Vehicle:
    def __init__(self, brand):
        self.__brand = brand     # private
    def move(self): ...

class Car(Vehicle):
    def __init__(self, brand, doors):
        super().__init__(brand)
        self.doors = doors       # public (+)
    def move(self): ...

For the exercise about the shapes class diagram, read the diagram like this: each rectangle is a class, each arrow an inheritance, and the +, # and - symbols tell which attributes take a single underscore, a double underscore or none. Remember that in Python the protection is a convention (you saw it in the access control article).