5.13. OOP Recap

5.13.1. Assignments

# %% About
# - Name: OOP AttributeSlots Repr
# - Difficulty: medium
# - Lines: 2
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define method `__repr__` which prints class name and all values
#    positionally, ie. `User('Alice', 'Apricot', 30)`
# 2. Use `dump()` function
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj metodę `__repr__` wypisującą nazwę klasy i wszystkie
#    wartości atrybutów pozycyjnie, np. `User('Alice', 'Apricot', 30)`
# 2. Użyj funkcji `dump()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# [User('Alice', 'Apricot', 30),
#  User('Bob', 'Blackthorn', 31),
#  User('Carol', 'Corn', 32),
#  User('Dave', 'Durian', 33),
#  User('Eve', 'Elderberry', 34),
#  User('Mallory', 'Melon', 15)]

# %% Hints
# - `self.__class__.__name__`
# - `tuple()`
# - `dict.values()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> User.__slots__
('firstname', 'lastname', 'age')

>>> from pprint import pprint
>>>
>>> result = [User(*row) for row in DATA[1:]]
>>> pprint(result)
[User('Alice', 'Apricot', 30),
 User('Bob', 'Blackthorn', 31),
 User('Carol', 'Corn', 32),
 User('Dave', 'Durian', 33),
 User('Eve', 'Elderberry', 34),
 User('Mallory', 'Melon', 15)]
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
__repr__: Callable[[object], str]

# %% Data
DATA = [
    ('firstname', 'lastname', 'age'),
    ('Alice', 'Apricot', 30),
    ('Bob', 'Blackthorn', 31),
    ('Carol', 'Corn', 32),
    ('Dave', 'Durian', 33),
    ('Eve', 'Elderberry', 34),
    ('Mallory', 'Melon', 15),
]

def dump(obj) -> dict:
    return {x:getattr(obj,x) for x in obj.__slots__}


# %% Result
class User:
    __slots__ = ('firstname', 'lastname', 'age')

    def __init__(self, firstname, lastname, age):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age

    def __repr__(self):
        clsname = self.__class__.__name__
        ...