Project 3 · 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 Resource:
    @property
    def category(self):
        return type(self).__name__.lower()

class Storage(Resource): pass
class HDD(Storage): pass

print(Resource().category, HDD().category)
2. What does this print?
class Storage:
    def __repr__(self):
        return f'{type(self).__name__.lower()}: 512 GB'

class SSD(Storage):
    def __repr__(self):
        return f'{super().__repr__()} (SATA III)'

print(repr(SSD()))
3. The project stores counts in self._total and exposes them with a getter-only @property def total(self). What happens on cpu.total = 100?
4. What does this print?
def validate_integer(name, value, min_value=None):
    if not isinstance(value, int):
        raise TypeError(f'{name} must be an integer.')
    if min_value is not None and value < min_value:
        raise ValueError(f'{name} too small')

try:
    validate_integer('num', True, 1)
    print('accepted')
except (TypeError, ValueError) as ex:
    print(type(ex).__name__)
5. What does this print?
class Resource:
    def __init__(self, total):
        self._total = total
    @property
    def total(self):
        return self._total

class CPU(Resource):
    def __init__(self, total, cores):
        self._cores = cores

try:
    print(CPU(10, 8).total)
except AttributeError:
    print('AttributeError')
6. Why does the design put capacity_gb in an intermediate Storage class instead of in HDD and SSD separately?
7. What is the MRO of SSD in the project's hierarchy?
class Resource: pass
class Storage(Resource): pass
class SSD(Storage): pass

print([c.__name__ for c in SSD.__mro__])
8. Suppose Resource declared __slots__ = ('_name', '_manufacturer', '_total', '_allocated') but CPU declared no __slots__. Which is true of a CPU instance?

Coding exercises

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

Exercise 1: Goal 1: validate_integer

Write validate_integer(arg_name, arg_value, min_value=None, max_value=None, custom_min_message=None, custom_max_message=None):

- if arg_value isn't an int, raise TypeError with a message containing arg_name, - if min_value is given and arg_value < min_value, raise ValueError; its message is custom_min_message if one was given, otherwise a default message that contains arg_name and min_value, - likewise for max_value with arg_value > max_value and custom_max_message, - otherwise return None. Both bounds are inclusive and optional.

Hints (3)
  1. isinstance(arg_value, int) handles the type check.
  2. Compare with is not None, not truthiness: min_value=0 is a real bound.
  3. Check the custom message first inside each bound check, and fall back to an f-string default.
Show a solution
def validate_integer(
        arg_name, arg_value, min_value=None, max_value=None,
        custom_min_message=None, custom_max_message=None
):
    if not isinstance(arg_value, int):
        raise TypeError(f'{arg_name} must be an integer.')
    if min_value is not None and arg_value < min_value:
        if custom_min_message is not None:
            raise ValueError(custom_min_message)
        raise ValueError(f'{arg_name} cannot be less than {min_value}')
    if max_value is not None and arg_value > max_value:
        if custom_max_message is not None:
            raise ValueError(custom_max_message)
        raise ValueError(f'{arg_name} cannot be greater than {max_value}')

Exercise 2: Goal 2: the Resource base class

Using the given validate_integer, write Resource(name, manufacturer, total, allocated):

- read-only properties name, manufacturer, total and allocated, stored in private attributes (_name, _total, …), - total must be an integer >= 0, allocated an integer between 0 and total (TypeError / ValueError otherwise), - computed properties available (total - allocated) and category (the instance's class name in lower case), - str() returns the name; repr() returns e.g. 'Parrot (resource - Pirates A-Hoy) : total=100, allocated=50', - claim(n) allocates n items (1 <= n <= available), freeup(n) returns n items to the pool (1 <= n <= allocated), died(n) removes n allocated items from both allocated and total (1 <= n <= allocated), and purchased(n) adds n >= 1 items to the total. Invalid n raises ValueError (or TypeError for non-integers).

Hints (3)
  1. Each property is a getter only, e.g. @property def total(self): return self._total.
  2. type(self).__name__.lower() gives the category for any subclass.
  3. The bounds for claim depend on the current state: validate_integer('num', num, 1, self.available).
Show a solution
def validate_integer(
        arg_name, arg_value, min_value=None, max_value=None,
        custom_min_message=None, custom_max_message=None
):
    if not isinstance(arg_value, int):
        raise TypeError(f'{arg_name} must be an integer.')
    if min_value is not None and arg_value < min_value:
        if custom_min_message is not None:
            raise ValueError(custom_min_message)
        raise ValueError(f'{arg_name} cannot be less than {min_value}')
    if max_value is not None and arg_value > max_value:
        if custom_max_message is not None:
            raise ValueError(custom_max_message)
        raise ValueError(f'{arg_name} cannot be greater than {max_value}')


class Resource:
    def __init__(self, name, manufacturer, total, allocated):
        self._name = name
        self._manufacturer = manufacturer
        validate_integer('total', total, min_value=0)
        self._total = total
        validate_integer(
            'allocated', allocated, 0, total,
            custom_max_message='Allocated inventory cannot exceed total inventory'
        )
        self._allocated = allocated

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

    @property
    def manufacturer(self):
        return self._manufacturer

    @property
    def total(self):
        return self._total

    @property
    def allocated(self):
        return self._allocated

    @property
    def category(self):
        return type(self).__name__.lower()

    @property
    def available(self):
        return self.total - self.allocated

    def __str__(self):
        return self.name

    def __repr__(self):
        return (f'{self.name} ({self.category} - {self.manufacturer}) : '
                f'total={self.total}, allocated={self.allocated}')

    def claim(self, num):
        validate_integer('num', num, 1, self.available,
                         custom_max_message='Cannot claim more than available')
        self._allocated += num

    def freeup(self, num):
        validate_integer('num', num, 1, self.allocated,
                         custom_max_message='Cannot return more than allocated')
        self._allocated -= num

    def died(self, num):
        validate_integer('num', num, 1, self.allocated,
                         custom_max_message='Cannot retire more than allocated')
        self._total -= num
        self._allocated -= num

    def purchased(self, num):
        validate_integer('num', num, 1)
        self._total += num

Exercise 3: Goal 3: the CPU class

validate_integer and Resource are given. Write CPU(Resource), created with CPU(name, manufacturer, total, allocated, cores, socket, power_watts):

- delegate the first four arguments to Resource.__init__ with super() (don't repeat its assignments or validation), - cores and power_watts must be integers >= 1; store all three new values privately and expose them as read-only properties cores, socket and power_watts, - override __repr__ so it contains the category, name, socket and number of cores, e.g. 'cpu: Ryzen 7 2700 (AM4 - x8)', - everything else (claim, available, category, str() …) is inherited, so don't redefine it.

Hints (3)
  1. Start __init__ with super().__init__(name, manufacturer, total, allocated).
  2. Validate with validate_integer('cores', cores, 1) before storing.
  3. Inside __repr__, self.category already returns 'cpu'.
Show a solution
def validate_integer(
        arg_name, arg_value, min_value=None, max_value=None,
        custom_min_message=None, custom_max_message=None
):
    if not isinstance(arg_value, int):
        raise TypeError(f'{arg_name} must be an integer.')
    if min_value is not None and arg_value < min_value:
        if custom_min_message is not None:
            raise ValueError(custom_min_message)
        raise ValueError(f'{arg_name} cannot be less than {min_value}')
    if max_value is not None and arg_value > max_value:
        if custom_max_message is not None:
            raise ValueError(custom_max_message)
        raise ValueError(f'{arg_name} cannot be greater than {max_value}')


class Resource:
    def __init__(self, name, manufacturer, total, allocated):
        self._name = name
        self._manufacturer = manufacturer
        validate_integer('total', total, min_value=0)
        self._total = total
        validate_integer(
            'allocated', allocated, 0, total,
            custom_max_message='Allocated inventory cannot exceed total inventory'
        )
        self._allocated = allocated

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

    @property
    def manufacturer(self):
        return self._manufacturer

    @property
    def total(self):
        return self._total

    @property
    def allocated(self):
        return self._allocated

    @property
    def category(self):
        return type(self).__name__.lower()

    @property
    def available(self):
        return self.total - self.allocated

    def __str__(self):
        return self.name

    def __repr__(self):
        return (f'{self.name} ({self.category} - {self.manufacturer}) : '
                f'total={self.total}, allocated={self.allocated}')

    def claim(self, num):
        validate_integer('num', num, 1, self.available,
                         custom_max_message='Cannot claim more than available')
        self._allocated += num

    def freeup(self, num):
        validate_integer('num', num, 1, self.allocated,
                         custom_max_message='Cannot return more than allocated')
        self._allocated -= num

    def died(self, num):
        validate_integer('num', num, 1, self.allocated,
                         custom_max_message='Cannot retire more than allocated')
        self._total -= num
        self._allocated -= num

    def purchased(self, num):
        validate_integer('num', num, 1)
        self._total += num


class CPU(Resource):
    def __init__(self, name, manufacturer, total, allocated,
                 cores, socket, power_watts):
        super().__init__(name, manufacturer, total, allocated)
        validate_integer('cores', cores, 1)
        validate_integer('power_watts', power_watts, 1)
        self._cores = cores
        self._socket = socket
        self._power_watts = power_watts

    @property
    def cores(self):
        return self._cores

    @property
    def socket(self):
        return self._socket

    @property
    def power_watts(self):
        return self._power_watts

    def __repr__(self):
        return f'{self.category}: {self.name} ({self.socket} - x{self.cores})'

Exercise 4: Goal 4: Storage, HDD and SSD

validate_integer and Resource are given. Write three classes, each delegating to its parent's __init__ with super():

- Storage(Resource): adds capacity_gb, an integer >= 1, as a read-only property. Its repr is '<category>: <capacity_gb> GB', e.g. 'storage: 512 GB'. - HDD(Storage): adds size, which must be '2.5"' or '3.5"' (otherwise ValueError), and rpm, an integer between 1_000 and 50_000 inclusive. Its repr extends the parent's using super().__repr__(): 'hdd: 1000 GB (3.5", 10000 rpm)'. - SSD(Storage): adds interface (any string). Its repr extends the parent's too: 'ssd: 1000 GB (SATA III)'.

All new attributes are read-only properties.

Hints (3)
  1. Each __init__ starts with super().__init__(...), passing everything the parent needs; HDD and SSD pass capacity_gb on to Storage.
  2. Check the size with if size not in ['2.5"', '3.5"']: raise ValueError(...).
  3. In HDD.__repr__, return f'{super().__repr__()} ({self.size}, {self.rpm} rpm)'.
Show a solution
def validate_integer(
        arg_name, arg_value, min_value=None, max_value=None,
        custom_min_message=None, custom_max_message=None
):
    if not isinstance(arg_value, int):
        raise TypeError(f'{arg_name} must be an integer.')
    if min_value is not None and arg_value < min_value:
        if custom_min_message is not None:
            raise ValueError(custom_min_message)
        raise ValueError(f'{arg_name} cannot be less than {min_value}')
    if max_value is not None and arg_value > max_value:
        if custom_max_message is not None:
            raise ValueError(custom_max_message)
        raise ValueError(f'{arg_name} cannot be greater than {max_value}')


class Resource:
    def __init__(self, name, manufacturer, total, allocated):
        self._name = name
        self._manufacturer = manufacturer
        validate_integer('total', total, min_value=0)
        self._total = total
        validate_integer(
            'allocated', allocated, 0, total,
            custom_max_message='Allocated inventory cannot exceed total inventory'
        )
        self._allocated = allocated

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

    @property
    def manufacturer(self):
        return self._manufacturer

    @property
    def total(self):
        return self._total

    @property
    def allocated(self):
        return self._allocated

    @property
    def category(self):
        return type(self).__name__.lower()

    @property
    def available(self):
        return self.total - self.allocated

    def __str__(self):
        return self.name

    def __repr__(self):
        return (f'{self.name} ({self.category} - {self.manufacturer}) : '
                f'total={self.total}, allocated={self.allocated}')

    def claim(self, num):
        validate_integer('num', num, 1, self.available,
                         custom_max_message='Cannot claim more than available')
        self._allocated += num

    def freeup(self, num):
        validate_integer('num', num, 1, self.allocated,
                         custom_max_message='Cannot return more than allocated')
        self._allocated -= num

    def died(self, num):
        validate_integer('num', num, 1, self.allocated,
                         custom_max_message='Cannot retire more than allocated')
        self._total -= num
        self._allocated -= num

    def purchased(self, num):
        validate_integer('num', num, 1)
        self._total += num


class Storage(Resource):
    def __init__(self, name, manufacturer, total, allocated, capacity_gb):
        super().__init__(name, manufacturer, total, allocated)
        validate_integer('capacity_gb', capacity_gb, 1)
        self._capacity_gb = capacity_gb

    @property
    def capacity_gb(self):
        return self._capacity_gb

    def __repr__(self):
        return f'{self.category}: {self.capacity_gb} GB'


class HDD(Storage):
    def __init__(self, name, manufacturer, total, allocated, capacity_gb,
                 size, rpm):
        super().__init__(name, manufacturer, total, allocated, capacity_gb)
        allowed_sizes = ['2.5"', '3.5"']
        if size not in allowed_sizes:
            raise ValueError(f'Invalid HDD size. Must be one of {", ".join(allowed_sizes)}')
        validate_integer('rpm', rpm, min_value=1_000, max_value=50_000)
        self._size = size
        self._rpm = rpm

    @property
    def size(self):
        return self._size

    @property
    def rpm(self):
        return self._rpm

    def __repr__(self):
        return f'{super().__repr__()} ({self.size}, {self.rpm} rpm)'


class SSD(Storage):
    def __init__(self, name, manufacturer, total, allocated, capacity_gb,
                 interface):
        super().__init__(name, manufacturer, total, allocated, capacity_gb)
        self._interface = interface

    @property
    def interface(self):
        return self._interface

    def __repr__(self):
        return f'{super().__repr__()} ({self.interface})'