Polymorphism and Special Methods · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
class Item:
    def __repr__(self):
        return 'R'
    def __str__(self):
        return 'S'

i = Item()
print([i], i)
2. A class defines __str__ but not __repr__. What does repr(obj) return?
3. Your __add__ receives an operand type it can't handle. What should it do?
4. What happens here?
class V:
    def __mul__(self, other):
        return 'V.__mul__'

print(V() * 3)
print(3 * V())
5. What does this print?
class A:
    def __add__(self, other):
        return NotImplemented
    def __radd__(self, other):
        return 'radd'

try:
    print(A() + A())
except TypeError:
    print('TypeError')
6. What does this print?
class Bag:
    def __init__(self):
        self.items = []
    def __iadd__(self, item):
        self.items.append(item)

b = Bag()
b += 'apple'
print(b)
7. What does this print?
class Box:
    def __init__(self, n):
        self.n = n
    def __lt__(self, other):
        return self.n < other.n

print(Box(2) > Box(1))
8. Which statement about functools.total_ordering is correct?
9. What does this print?
class Person:
    def __init__(self, name):
        self.name = name
    def __eq__(self, other):
        return isinstance(other, Person) and self.name == other.name

try:
    s = {Person('Ann')}
    print(len(s))
except TypeError as ex:
    print('TypeError')
10. What does this print?
class Weird:
    def __len__(self):
        return 0
    def __bool__(self):
        return True

print(bool(Weird()))
11. In CPython, when is __del__ called?
12. What does this print?
class Temp:
    def __str__(self):
        return '21C'

try:
    print(f'[{Temp():>6}]')
except TypeError:
    print('TypeError')

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: A 2-D vector with operators

Complete the Vector2D class so that it supports:

- v + w and v - w for two Vector2D objects (component by component), - v * k and k * v for a real number k (numbers.Real), scaling both components, - -v (negate both components) and abs(v) (the Euclidean length, a float).

For any operand the class can't handle, the operator methods must **return NotImplemented**, so that for example v + 1 raises a TypeError.

Hints (3)
  1. Each binary method starts with a type check: if not isinstance(other, ...): return NotImplemented.
  2. 3 * v first tries int.__mul__, which gives up; Python then calls v.__rmul__(3). Since scaling is commutative, __rmul__ can return self * other.
  3. math.hypot(x, y) computes the length sqrt(x**2 + y**2).
Show a solution
from numbers import Real
from math import hypot

class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'Vector2D({self.x!r}, {self.y!r})'

    def __eq__(self, other):
        if isinstance(other, Vector2D):
            return (self.x, self.y) == (other.x, other.y)
        return NotImplemented

    def __add__(self, other):
        if not isinstance(other, Vector2D):
            return NotImplemented
        return Vector2D(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        if not isinstance(other, Vector2D):
            return NotImplemented
        return Vector2D(self.x - other.x, self.y - other.y)

    def __mul__(self, other):
        if not isinstance(other, Real):
            return NotImplemented
        return Vector2D(self.x * other, self.y * other)

    def __rmul__(self, other):
        return self * other

    def __neg__(self):
        return Vector2D(-self.x, -self.y)

    def __abs__(self):
        return hypot(self.x, self.y)

Exercise 2: Comparable, hashable versions

Write a class Version built from a string like '1.2.3':

- str(v) returns the original string and repr(v) returns Version('1.2.3'). - Versions compare numerically part by part, so Version('1.10') > Version('1.9'). - Trailing zeros don't matter: Version('1.2') == Version('1.2.0'). - Support all of ==, !=, <, <=, >, >= (use functools.total_ordering). - Instances are hashable, consistently with ==. - Comparing with anything that isn't a Version must use NotImplemented, so == gives False and < raises TypeError.

Tip: store a tuple of ints with the trailing zeros stripped, and base __eq__, __lt__ and __hash__ on it.

Hints (3)
  1. Tuples of ints already compare element by element: (1, 10) > (1, 9) is True.
  2. Strip trailing zeros (while parts and parts[-1] == 0: parts.pop()) so 1.2 and 1.2.0 get the same key.
  3. Defining __eq__ removes the inherited hash: add __hash__ returning hash(self._key).
Show a solution
from functools import total_ordering

@total_ordering
class Version:
    def __init__(self, text):
        self.text = text
        parts = [int(p) for p in text.split('.')]
        while len(parts) > 1 and parts[-1] == 0:
            parts.pop()
        self._key = tuple(parts)

    def __str__(self):
        return self.text

    def __repr__(self):
        return f'Version({self.text!r})'

    def __eq__(self, other):
        if isinstance(other, Version):
            return self._key == other._key
        return NotImplemented

    def __lt__(self, other):
        if isinstance(other, Version):
            return self._key < other._key
        return NotImplemented

    def __hash__(self):
        return hash(self._key)

Exercise 3: A call-counting decorator class

Write a decorator class CountCalls:

- @CountCalls above a function replaces it with a CountCalls instance. - Calling the instance calls the original function with all positional and keyword arguments and returns its result. - The attribute calls holds how many times it has been called; the method reset() sets it back to 0. - The decorated function keeps its __name__ and __doc__ (use functools.update_wrapper).

Hints (2)
  1. __init__ receives the function being decorated; __call__(self, *args, **kwargs) runs every time the decorated name is called.
  2. update_wrapper(self, fn) copies __name__, __doc__ and friends onto the instance.
Show a solution
from functools import update_wrapper

class CountCalls:
    def __init__(self, fn):
        self.fn = fn
        self.calls = 0
        update_wrapper(self, fn)

    def __call__(self, *args, **kwargs):
        self.calls += 1
        return self.fn(*args, **kwargs)

    def reset(self):
        self.calls = 0

Exercise 4: Formatting money

Complete the Money class (an amount and a currency code):

- str(m) returns the amount with two decimals followed by the currency: str(Money(12.5, 'EUR')) is '12.50 EUR'. - format(m, spec) (and so f'{m:spec}') formats the amount with spec and appends the currency: f'{Money(1234.5):,.2f}' is '1,234.50 USD'. With an empty spec, it returns str(m). - bool(m) is False for a zero amount and True otherwise.

Hints (2)
  1. Delegate: format(self.amount, spec) does all the hard work of interpreting the spec.
  2. __bool__ must return a real bool: self.amount != 0 does.
Show a solution
class Money:
    def __init__(self, amount, currency='USD'):
        self.amount = amount
        self.currency = currency

    def __repr__(self):
        return f'Money({self.amount!r}, {self.currency!r})'

    def __str__(self):
        return f'{self.amount:.2f} {self.currency}'

    def __format__(self, spec):
        if not spec:
            return str(self)
        return f'{format(self.amount, spec)} {self.currency}'

    def __bool__(self):
        return self.amount != 0