4.2. Inheritance Single

4.2.1. Example

>>> class Account:
...     pass
>>>
>>> class User(Account):
...     pass
>>>
>>> class Admin(Account):
...     pass

4.2.2. Diagram

../../_images/inheritance-usecase-single.png

4.2.3. Code

class Account:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname


class User(Account):
    pass


class Staff(Account):
    def astuple(self):
        data = vars(self).values()
        return tuple(data)


class Admin(Account):
    def astuple(self):
        data = vars(self).values()
        return tuple(data)

    def asdict(self):
        data = vars(self)
        return dict(data)

4.2.4. Assignments

# %% 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

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

# %% About
# - Name: Inheritance Single A
# - Difficulty: easy
# - Lines: 6
# - Minutes: 3

# %% English
# 1. Define class `Account`
# 2. Define class `User` inheriting from `Account`
# 3. Define class `Admin` inheriting from `Account`
# 4. Use single inheritance
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj klasę `Account`
# 2. Zdefiniuj klasę `User` dziedziczącą po `Account`
# 3. Zdefiniuj klasę `Admin` dziedziczącą po `Account`
# 4. Użyj pojedynczego dziedziczenia
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isclass

>>> assert isclass(Account)
>>> assert isclass(User)
>>> assert isclass(Admin)

>>> assert issubclass(User, Account)
>>> assert issubclass(Admin, Account)

>>> assert not issubclass(User, Admin)
>>> assert not issubclass(Admin, User)
"""

# Define class `Account`
# Define class `User` inheriting from `Account`
# Define class `Admin` inheriting from `Account`
# Use single inheritance
# type: type[Account]
...