Python Classes and Objects · Lesson 86 of 149

Python Polymorphism and super()

What you will learn

  • What polymorphism is
  • Duck typing: using objects by what they do, not what they are
  • LBYL and EAFP: checking first, or trying and handling errors
  • How built-in functions and operators are polymorphic
  • How super() chains __init__ and other methods
  • Why a subclass should keep its parent's method signature compatible

1. One call, many behaviours

Polymorphism (from Greek: "many forms") means that the same method call can do different things, depending on the object. You write code that asks an object to do something, and each object responds in its own way:

class Shape:
    def area(self):
        raise NotImplementedError

    def __str__(self):
        return f"{type(self).__name__}(area={self.area():.2f})"

class Rect(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14159 * self.r ** 2

class Tri(Shape):
    def __init__(self, b, h):
        self.b, self.h = b, h

    def area(self):
        return 0.5 * self.b * self.h

shapes = [Rect(2, 3), Circle(1), Tri(4, 5)]
for s in shapes:
    print(s)
print(round(sum(s.area() for s in shapes), 2))
print(max(shapes, key=lambda s: s.area()))
Rect(area=6.00)
Circle(area=3.14)
Tri(area=10.00)
19.14
Tri(area=10.00)

The loop and the sum do not check what kind of shape each one is. They just call s.area(). Add a fourth shape class tomorrow, and this code works without any change. That is the power of polymorphism: code that works with many types, and does not need to know them all.

Quick check: in `sum(s.area() for s in shapes)`, how does Python know which `area` to run?

It uses the class of each object: Rect.area for a rectangle, Circle.area for a circle, and so on.

2. Duck typing

Python goes further than most languages: inheritance is not needed for polymorphism. If an object has the method you call, it works. This is called duck typing, from the saying: "If it walks like a duck and quacks like a duck, it is a duck." What matters is what the object can do, not what class it belongs to:

class Dog:
    def speak(self):
        return "Woof"

class Cat:
    def speak(self):
        return "Meow"

class Robot:
    def speak(self):
        return "Beep"

def make_noise(thing):
    return thing.speak()

print([make_noise(x) for x in [Dog(), Cat(), Robot()]])
['Woof', 'Meow', 'Beep']

Dog, Cat and Robot share no parent class, yet make_noise works for all three. The only "contract" is: has a speak() method that takes no arguments.

If an object does not have the method, you get an AttributeError at the call:

class Rock:
    pass

make_noise(Rock())
AttributeError: 'Rock' object has no attribute 'speak'

This is why classes that follow a pattern (the protocol) can be used together even when written by different people.

3. Ask permission, or ask forgiveness

What if you are not sure that the object can do the job? Python has two styles:

Style Meaning Looks like
LBYL: "look before you leap" check first if hasattr(thing, "speak"): ...
EAFP: "easier to ask forgiveness than permission" try it, handle the failure try: ... except AttributeError: ...
def safe_noise(thing):
    return thing.speak() if hasattr(thing, "speak") else "(silence)"

def eafp(thing):
    try:
        return thing.speak()
    except AttributeError:
        return "(silence)"

print(safe_noise(Rock()), safe_noise(Dog()))
print(eafp(Rock()), eafp(Cat()))
(silence) Woof
(silence) Meow

Both work. Python programmers usually prefer EAFP, because it is shorter in the common case, and avoids a gap between the check and the use. But note: with try/except AttributeError, an AttributeError raised inside speak itself would be hidden too, so keep the try block small. Exceptions are chapter 14.

Checking with isinstance against a class is the third option, which is less flexible: it rejects a perfectly good duck that is not a subclass.

4. Polymorphism is everywhere in Python

You have used it all along:

print(len("abc"), len([1, 2]), len({"a": 1}), len(range(5)))
print(1 + 2, "a" + "b", [1] + [2], (1,) + (2,))
print(max("abc"), max([3, 1]), max((2, 9)))
3 2 1 5
3 ab [1, 2] (1, 2)
c 3 9
  • len works on strings, lists, dictionaries and ranges.
  • + adds numbers, joins text and joins lists.
  • max, sorted and sum work on any iterable (lesson 12.4).

How? Each of these types implements the same special methods (__len__, __add__, __iter__), and the built-in function calls them. Your own classes can do the same, and then plug into len, +, for and more (lessons 13.7 and 13.8). For example, a class with __len__ and __iter__ works with len, sum, max, in and sorted:

class Stack:
    def __init__(self):
        self._items = []

    def push(self, x):
        self._items.append(x)

    def __len__(self):
        return len(self._items)

    def __iter__(self):
        return reversed(self._items)

s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(len(s), list(s), sum(s), max(s), 2 in s, sorted(s))
3 [3, 2, 1] 6 3 True [1, 2, 3]

A Stack is not a list, yet it behaves like a collection, because it follows the protocol.

5. super() builds chains

In lesson 13.5 you used super().__init__() to run the parent's initialiser. With several levels, each class calls up to the next, and the order is easy to trace:

class A:
    def __init__(self):
        print("A.__init__")
        self.a = 1

class B(A):
    def __init__(self):
        print("B.__init__ start")
        super().__init__()
        self.b = 2
        print("B.__init__ end")

class C(B):
    def __init__(self):
        print("C.__init__ start")
        super().__init__()
        self.c = 3

c = C()
print(vars(c))
print([k.__name__ for k in C.__mro__])
C.__init__ start
B.__init__ start
A.__init__
B.__init__ end
{'a': 1, 'b': 2, 'c': 3}
['C', 'B', 'A', 'object']

The calls go up the chain (C, then B, then A), and A finishes first, then B, then C. Every class adds its own attributes after the parent has set up its own.

Layering a method

super() works for any method, not only __init__. Each class can add a layer around the parent's result:

class Logger:
    def log(self, msg):
        return f"LOG: {msg}"

class TimeLogger(Logger):
    def log(self, msg):
        return "12:00 " + super().log(msg)

class ShoutLogger(TimeLogger):
    def log(self, msg):
        return super().log(msg).upper()

print(Logger().log("hi"))
print(TimeLogger().log("hi"))
print(ShoutLogger().log("hi"))
LOG: hi
12:00 LOG: hi
12:00 LOG: HI

ShoutLogger.log asks its parent (TimeLogger) to do its part, which asks its parent (Logger); then each layer changes the result on the way back.

Passing extra arguments up

When a parent takes arguments that the child does not need to know about, use **kwargs to pass them up (lesson 11.4):

class Base:
    def __init__(self, **kwargs):
        self.options = kwargs

class Derived(Base):
    def __init__(self, extra, **kwargs):
        super().__init__(**kwargs)
        self.extra = extra

d = Derived("x", a=1, b=2)
print(d.extra, d.options)
x {'a': 1, 'b': 2}

The older form

You may see super(Old, self).__init__() in older code. It means the same as super().__init__(), which is the form to use in Python 3. Plain super() works inside methods of a class.

6. Keep the signature compatible

Polymorphism only works if callers can treat a subclass like its parent. So an overriding method should accept at least what the parent's accepts, and return the same kind of thing. This is the Liskov substitution principle: anywhere the parent works, the child should work too.

class Parent:
    def greet(self, name):
        return f"Hello {name}"

class GoodChild(Parent):
    def greet(self, name, excited=False):
        base = super().greet(name)
        return base + "!" if excited else base

print(GoodChild().greet("A"))
print(GoodChild().greet("A", excited=True))
print(Parent().greet("A"))
Hello A
Hello A!
Hello A

GoodChild.greet accepts everything the parent's did, plus an optional extra. It is a safe replacement. Compare:

class BadChild(Parent):
    def greet(self):
        return "no name"

BadChild().greet("A")
TypeError: BadChild.greet() takes 1 positional argument but 2 were given

BadChild dropped the name parameter. Any code written for a Parent (obj.greet("A")) breaks when handed a BadChild. Rules of thumb for overrides:

  • keep the same parameters (you may add optional ones);
  • return the same kind of value;
  • do not make it require more than the parent did.

7. Choosing between inheritance and duck typing

Situation Choose
the classes share real code (an __init__, helper methods) inheritance
the classes just happen to have the same method names duck typing, no parent needed
you want to force every subclass to define certain methods an abstract base class (lesson 13.10)
you want to document the expected methods without forcing a protocol with type hints (lesson 19.2)

Worked example: paying by any method

A shop's checkout function must work with any payment method, as long as it has pay(amount). The classes are unrelated, and one of the objects is not a payment method at all.

class CardPayment:
    def __init__(self, number):
        self.number = number

    def pay(self, amount):
        return f"charged {amount} to card ending {self.number[-4:]}"


class WalletPayment:
    def __init__(self, balance):
        self.balance = balance

    def pay(self, amount):
        if amount > self.balance:
            raise ValueError("wallet too low")
        self.balance -= amount
        return f"paid {amount} from wallet, {self.balance} left"


class Cash:
    def pay(self, amount):
        return f"took {amount} in cash"


class Voucher:
    pass


def checkout(method, amount):
    try:
        return method.pay(amount)
    except ValueError as e:
        return f"failed: {e}"
    except AttributeError:
        return f"{type(method).__name__} cannot pay"


methods = [CardPayment("1234567812345678"), WalletPayment(50), Cash(), Voucher(), WalletPayment(10)]
for m in methods:
    print(checkout(m, 30))
print(sum(1 for m in methods if hasattr(m, "pay")))
charged 30 to card ending 5678
paid 30 from wallet, 20 left
took 30 in cash
Voucher cannot pay
failed: wallet too low
4
Idea In the example
polymorphism method.pay(amount) does the right thing for each class
duck typing there is no shared parent; having pay is enough
EAFP checkout tries the call and handles AttributeError for an object that cannot pay
a protocol any new class with a pay(amount) method can be added later

hasattr counted four objects that can pay. The card number and amounts are made up.

Common mistakes

  • Checking isinstance against a class when only a method matters, which rejects good "ducks".
  • A big try block around .method() that hides unrelated AttributeErrors.
  • Overriding with a different signature, so that parent-based code breaks.
  • Forgetting super().__init__() in a chain (lesson 13.5).
  • Writing if type(x) == A ... elif type(x) == B ... when each class could have its own method.
  • Depending on a method that not every object has, without a check or a try.

Key takeaways

  • Polymorphism: one method call, different behaviour depending on the object's class, so code does not need to know all the types.
  • Duck typing: an object is usable if it has the methods you call; inheritance is not required.
  • EAFP (try / except) is the usual Python style; LBYL uses hasattr; keep try blocks small.
  • Built-in functions and operators are polymorphic through special methods (__len__, __iter__, __add__); your classes can join in.
  • super() chains calls up the inheritance line; an override should keep the parent's signature compatible.

Practice

1. What is polymorphism, in one sentence?

Show answer

Calling the same method on different objects gives behaviour that depends on each object's own class.

2. Does a function that calls thing.speak() need thing to inherit from a particular class?

Show answer

No. Any object that has a suitable speak() method works (duck typing).

3. Write the EAFP version of "call obj.close() if it exists".

Show answer
try:
    obj.close()
except AttributeError:
    pass

4. In what order do __init__ messages appear for C(B(A)) when each calls super().__init__() in the middle?

Show answer

The starts go up (C, B, A), then the ends come back down (A finishes first, then B, then C).

5. Why is def greet(self): a bad override of def greet(self, name):?

Show answer

Code that calls obj.greet("A") on a parent breaks for the child with TypeError. An override should accept at least what the parent's version accepts.

6. Which special methods let your class work with len(x) and for item in x?

Show answer

__len__ and __iter__.