Single Inheritance · 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 Shape: pass
class Polygon(Shape): pass
class Rectangle(Polygon): pass
class Square(Rectangle): pass

sq = Square()
print(isinstance(sq, Polygon), type(sq) is Rectangle)
2. What happens when you call issubclass(obj, Shape) where obj = Shape()?
3. Which statement about the built-in object is false?
4. What does this print?
class Person:
    def __repr__(self):
        return 'Person()'

print(str(Person()))
5. What does this print?
class Shape:
    def info(self):
        return 'shape'
    def describe(self):
        return f'I am a {self.info()}'

class Circle(Shape):
    def info(self):
        return 'circle'

print(Circle().describe())
6. What does this print?
class Account:
    apr = 3.0
    def rate(self):
        return Account.apr

class Savings(Account):
    apr = 5.0

s = Savings()
s.apr = 10.0
print(s.rate(), s.apr, type(s).apr)
7. What does this print?
class Person:
    def __init__(self, name):
        self.name = name

class Student(Person):
    def __init__(self, name, number):
        self.number = number

s = Student('Alex', 42)
print(hasattr(s, 'name'), hasattr(s, 'number'))
8. What does this print?
class A:
    def go(self):
        return 'A'

class B(A):
    pass

class C(B):
    def go(self):
        return 'C' + super().go()

print(C().go())
9. What does this print?
class Person:
    def greet(self):
        return 'Hi from ' + self.name()
    def name(self):
        return 'Person'

class Student(Person):
    def greet(self):
        return super().greet() + '!'
    def name(self):
        return 'Student'

print(Student().greet())
10. What does this print?
class Person:
    __slots__ = ('name',)
    def __init__(self, name):
        self.name = name

class Student(Person):
    pass

s = Student('Alex')
s.age = 20
print(s.__dict__)
11. Which of these is not a consequence of declaring __slots__ = ('x', 'y') in a class (with no slot-less parents)?
12. What does this print?
class Point:
    def __init__(self, x):
        self.x = x
    def __eq__(self, other):
        return self.x == other.x

try:
    print(len({Point(1), Point(1)}))
except TypeError as ex:
    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 small shape hierarchy

Build three classes:

- Shape, the base class: - a read-only property name that returns the lower-case name of the instance's class (so it's 'square' for a Square, without any subclass having to set it), - a method area() that raises NotImplementedError, - a method describe() that returns f'{name} with area {area}', using the object's name and area(). - Rectangle(Shape), created with Rectangle(width, height), storing width and height and implementing area(). - Square(Rectangle), created with Square(side). It must delegate to Rectangle.__init__ with super(), and it must not define its own area or describe: those are inherited. Add a read-only property side.

For example, Square(3).describe() returns 'square with area 9'.

Hints (3)
  1. type(self).__name__ is the name of the instance's actual class, even when the code runs in Shape.
  2. describe can call self.area(): the lookup starts at the instance's class, so it finds Rectangle.area for squares too.
  3. In Square.__init__, call super().__init__(side, side).
Show a solution
class Shape:
    @property
    def name(self):
        return type(self).__name__.lower()

    def area(self):
        raise NotImplementedError(f'{type(self).__name__} must implement area()')

    def describe(self):
        return f'{self.name} with area {self.area()}'


class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height


class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)

    @property
    def side(self):
        return self.width

Exercise 2: Accounts that respect subclasses

The Account class below works on its own but breaks as soon as it's subclassed. Fix it, then write Savings.

Account:

- has a class attribute apr (percent per year) of 3.0, - interest() must return balance * apr / 100 using the apr of the instance's class, so subclasses that override apr are respected, but an instance attribute called apr is ignored, - describe() must start with the name of the instance's actual class, e.g. 'Savings #7: balance=100'.

Savings(Account):

- overrides apr with 5.0, - is created with Savings(number, balance, owner) and must delegate the first two arguments to Account.__init__ with super(), then store owner, - overrides describe() by extending the parent's result with ', owner=<owner>', using super().

Hints (3)
  1. Account.apr always means the attribute on Account. Which expression gives you the instance's class?
  2. self.apr would find an instance attribute first; type(self).apr skips the instance dictionary.
  3. In Savings.describe, call super().describe() and append to its result.
Show a solution
class Account:
    apr = 3.0

    def __init__(self, number, balance):
        self.number = number
        self.balance = balance

    def interest(self):
        return self.balance * type(self).apr / 100

    def describe(self):
        return f'{type(self).__name__} #{self.number}: balance={self.balance}'


class Savings(Account):
    apr = 5.0

    def __init__(self, number, balance, owner):
        super().__init__(number, balance)
        self.owner = owner

    def describe(self):
        return f'{super().describe()}, owner={self.owner}'

Exercise 3: A read-only, delegating property

Product (given) has a validated, writable price property. Write a subclass Discounted(Product):

- created with Discounted(name, price, discount); delegate name and price to Product.__init__ with super() (so the price is still validated), - discount must be a number with 0 <= discount < 1, otherwise raise ValueError; store it as self.discount, - override price with a read-only property that returns the parent's price reduced by the discount, rounded to 2 decimals (for example 100 with a discount of 0.25 gives 75.0), - add a read-only property full_price that returns the parent's (undiscounted) price.

Don't access _price directly in Discounted: get the parent's value through super().

Hints (3)
  1. Defining a property with only a getter makes it read-only; setting it raises AttributeError.
  2. Inside the new price getter, self.price would call itself forever. super().price runs Product's getter instead.
  3. Validate the discount after super().__init__(...), so an invalid price is reported first.
Show a solution
class Product:
    def __init__(self, name, price):
        self.name = name
        self._price = self._validated(price)

    @staticmethod
    def _validated(price):
        if isinstance(price, bool) or not isinstance(price, (int, float)) or price <= 0:
            raise ValueError('price must be a positive number')
        return price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        self._price = self._validated(value)


class Discounted(Product):
    def __init__(self, name, price, discount):
        super().__init__(name, price)
        if not isinstance(discount, (int, float)) or not 0 <= discount < 1:
            raise ValueError('discount must be in [0, 1)')
        self.discount = discount

    @property
    def price(self):
        return round(super().price * (1 - self.discount), 2)

    @property
    def full_price(self):
        return super().price

Exercise 4: Slotted points

Write three memory-efficient point classes:

- Point2D(x, y): stores x and y in slots, has no instance __dict__, and supports weak references (weakref.ref(p) must work). Its __repr__ returns e.g. 'Point2D(1, 2)', using the instance's class name. - Point3D(Point2D), created with Point3D(x, y, z): delegates x and y to the parent with super(), stores z in a slot, and still has no __dict__. Its __slots__ must list only the new name. repr gives 'Point3D(1, 2, 3)'. - TaggedPoint(Point2D), created like Point2D: keeps x and y in the inherited slots, but allows arbitrary extra attributes (such as t.label = 'home') by adding an instance dictionary through its slots.

Hints (3)
  1. Weak references need '__weakref__' in the slots of the class that first uses slots. Subclasses inherit it.
  2. A subclass without its own __slots__ gets a __dict__ back, so Point3D needs __slots__ = ('z',).
  3. TaggedPoint only needs __slots__ = ('__dict__',); x and y are already slots in Point2D.
Show a solution
class Point2D:
    __slots__ = ('x', 'y', '__weakref__')

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

    def __repr__(self):
        return f'{type(self).__name__}({self.x}, {self.y})'


class Point3D(Point2D):
    __slots__ = ('z',)

    def __init__(self, x, y, z):
        super().__init__(x, y)
        self.z = z

    def __repr__(self):
        return f'{type(self).__name__}({self.x}, {self.y}, {self.z})'


class TaggedPoint(Point2D):
    __slots__ = ('__dict__',)