Classes · 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 Account:
    rate = 1.0

a = Account()
b = Account()
a.rate = 2.0
Account.rate = 3.0
print(a.rate, b.rate)
2. What does this print?
class Team:
    members = []

t1 = Team()
t2 = Team()
t1.members.append('Alex')
print(t2.members, t1.__dict__)
3. What happens here?
class Config:
    debug = False

try:
    Config.__dict__['debug'] = True
    print(Config.debug)
except TypeError:
    print('TypeError')
4. What does this print?
class Greeter:
    def greet():
        return 'hi'

g = Greeter()
try:
    print(g.greet())
except TypeError:
    print('TypeError')
print(Greeter.greet())
5. What does this print?
class Person:
    pass

p = Person()
p.hello = lambda *args: len(args)
Person.hi = lambda *args: len(args)
print(p.hello(), p.hi())
6. What does this print?
class Tricky:
    __class__ = int

t = Tricky()
print(type(t).__name__, t.__class__.__name__)
7. When Person('Eric') runs and Person defines __init__(self, name), what is true?
8. What does this print?
class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

p = Person('Alex')
p.__dict__['name'] = 'Hacker'
print(p.name)
9. What does this print?
class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def set_name(self, value):
        self._name = value

p = Person('Alex')
try:
    p.name = 'Guido'
    print(p.name)
except AttributeError:
    print('AttributeError')
10. What does this print?
class Counter:
    count = 0

    @classmethod
    def bump(cls):
        cls.count += 1

c = Counter()
c.bump()
Counter.bump()
print(Counter.count, 'count' in c.__dict__)
11. What does this print?
x = 'global'

class Demo:
    x = 'class'
    direct = x
    listed = [x for _ in range(1)]

    def method(self):
        return x

print(Demo.direct, Demo.listed[0], Demo().method())
12. Which method type fits a helper that validates a value and needs neither the instance nor the class?

Coding exercises

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

Exercise 1: Validated, computed temperatures

Write a class Temperature that stores a temperature in degrees Celsius.

- Temperature(celsius) sets the initial value through the celsius property (so it's validated too). - celsius is a read/write property. Setting it to something that isn't a real number (use numbers.Real, and reject bool) raises TypeError; setting it below absolute zero (-273.15) raises ValueError. - fahrenheit is a read/write computed property: reading returns celsius * 9 / 5 + 32, assigning converts back and stores the result in celsius (with the same validation). - kelvin is a read-only computed property: celsius + 273.15.

Don't store fahrenheit or kelvin anywhere: only the Celsius value is kept, in _celsius.

Hints (3)
  1. Write celsius with @property and @celsius.setter; put all validation in the setter, and have __init__ assign self.celsius.
  2. bool is a subclass of int, so isinstance(True, numbers.Real) is True. Check for it explicitly.
  3. The fahrenheit setter can simply convert and assign self.celsius = ..., reusing the Celsius validation.
Show a solution
import numbers

class Temperature:
    ABSOLUTE_ZERO = -273.15

    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if not isinstance(value, numbers.Real) or isinstance(value, bool):
            raise TypeError('Temperature must be a real number.')
        if value < Temperature.ABSOLUTE_ZERO:
            raise ValueError('Temperature cannot be below absolute zero.')
        self._celsius = value

    @property
    def fahrenheit(self):
        return self.celsius * 9 / 5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        if not isinstance(value, numbers.Real) or isinstance(value, bool):
            raise TypeError('Temperature must be a real number.')
        self.celsius = (value - 32) * 5 / 9

    @property
    def kelvin(self):
        return self.celsius - Temperature.ABSOLUTE_ZERO

Exercise 2: Class attributes, class methods and static methods

Write a class Product with:

- __init__(self, name, price) storing name and price as instance attributes, and incrementing a class attribute count (starting at 0) that tracks how many products have been created. - a static method parse_price(text) that turns strings like '$1,299.50' or ' 12 ' into a float (strip whitespace, a leading $, and thousands commas). - a class method from_csv(cls, line) that takes 'name,price' (split on the first comma only, strip the name) and returns a new instance of cls, using parse_price for the price.

from_csv must use cls, so it also works for subclasses.

Hints (3)
  1. Increment the counter on the class: Product.count += 1. Writing self.count += 1 would create an instance attribute instead.
  2. line.split(',', 1) splits on the first comma only, so the price may contain thousands separators.
  3. Inside from_csv, call cls(...), not Product(...), so subclasses get instances of themselves.
Show a solution
class Product:
    count = 0

    def __init__(self, name, price):
        self.name = name
        self.price = price
        Product.count += 1

    @staticmethod
    def parse_price(text):
        return float(text.strip().lstrip('$').replace(',', ''))

    @classmethod
    def from_csv(cls, line):
        name, price = line.split(',', 1)
        return cls(name.strip(), cls.parse_price(price))

Exercise 3: A cached computed property

Write a class Rectangle(width, height) where:

- width and height are read/write properties. Setting either to a number that isn't positive raises ValueError. - area is a read-only property computed as width * height. It must be cached: computed only on the first read, and then again only after width or height has been changed. - every time the area is actually computed, increment an instance attribute computations (start it at 0), so the tests can check the cache. - del r.area clears the cache, so the next read recomputes.

Hints (3)
  1. Keep the cached value in _area, with None meaning "not computed yet".
  2. The width and height setters should reset _area to None. Since __init__ assigns through the setters, that also initializes the cache.
  3. Add @area.deleter to reset the cache. Without an @area.setter, the property stays read-only.
Show a solution
class Rectangle:
    def __init__(self, width, height):
        self.computations = 0
        self.width = width
        self.height = height

    @staticmethod
    def _validate(value):
        if value <= 0:
            raise ValueError('Sizes must be positive.')
        return value

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

    @width.setter
    def width(self, value):
        self._width = self._validate(value)
        self._area = None

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        self._height = self._validate(value)
        self._area = None

    @property
    def area(self):
        if self._area is None:
            self.computations += 1
            self._area = self.width * self.height
        return self._area

    @area.deleter
    def area(self):
        self._area = None

Exercise 4: Per-instance methods with MethodType

Write a class Robot with:

- __init__(self, name) storing name. - install(self, action_name, func): binds func to this robot with types.MethodType and stores the bound method on the instance under action_name, so robot.<action_name>(...) calls func(robot, ...). - perform(self, action_name, *args): calls the installed action with args and returns its result. If no such action was installed on this robot, raise AttributeError with a message that includes action_name.

Other robots must not be affected by an install, and Robot itself must not gain new attributes.

Hints (2)
  1. MethodType(func, self) creates a method bound to this robot; store it with setattr(self, action_name, ...).
  2. Look the action up in self.__dict__ (not with getattr), so methods of the class like install don't count as installed actions.
Show a solution
from types import MethodType

class Robot:
    def __init__(self, name):
        self.name = name

    def install(self, action_name, func):
        setattr(self, action_name, MethodType(func, self))

    def perform(self, action_name, *args):
        action = self.__dict__.get(action_name)
        if action is None:
            raise AttributeError(f'{self.name} has no action {action_name!r}')
        return action(*args)