4.5. Inheritance Composition

4.5.1. Example

>>> class UserPermissions:
...     pass
>>>
>>> class AdminPermissions:
...     pass
>>>
>>>
>>> class Account:
...     def __init__(self, permissions):
...         self.permissions = permissions
>>> mark = Account(UserPermissions())
>>> mark = Account(AdminPermissions())

4.5.2. Diagram

../../_images/inheritance-usecase-composition.png

4.5.3. Code

class TupleSerializer:
    def astuple(self, instance):
        data = [v for v in vars(instance).values()]
        return tuple(data)


class DictSerializer:
    def asdict(self, instance):
        data = {k: v for k, v in vars(instance).items()
                if not k.startswith('_')}
        return dict(data)


class Account:
    tuple_serializer: TupleSerializer | None
    dict_serializer: DictSerializer | None

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

    def astuple(self):
        if self.tuple_serializer is None:
            clsname = self.__class__.__name__
            error = f"'{clsname}' object has no attribute 'astuple'"
            raise AttributeError(error)
        return self.tuple_serializer.astuple(self)

    def asdict(self):
        if self.dict_serializer is None:
            clsname = self.__class__.__name__
            error = f"'{clsname}' object has no attribute 'asdict'"
            raise AttributeError(error)
        return self.dict_serializer.asdict(self)


class User(Account):
    tuple_serializer = None
    dict_serializer = None


class Staff(Account):
    tuple_serializer = TupleSerializer()
    dict_serializer = None


class Admin(Account):
    tuple_serializer = TupleSerializer()
    dict_serializer = DictSerializer()

4.5.4. Use Case - 1

>>> class UserPermissions:
...     pass
>>>
>>> class AdminPermissions:
...     pass
>>>
>>> class MyAccount:
...     permissions: UserPermissions | AdminPermissions
...
...     def __init__(self, permissions=UserPermissions()):
...         self.permissions = permissions

4.5.5. Use Case - 2

SetUp:

>>> import json
>>> from datetime import date

Naive example:

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
... }
>>>
>>> json.dumps(data)
'{"firstname": "Mark", "lastname": "Watney"}'

Let's add a birthdate:

>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'birthdate': date(1969, 7, 21),
... }
>>>
>>> json.dumps(data)
Traceback (most recent call last):
TypeError: Object of type date is not JSON serializable

If you want to use your better version of encoder (for example which can encode date object. You can create a class which inherits from default json.JSONEncoder and overwrite .default() method. Here's the solution:

>>> class MyEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, date):
...             return obj.isoformat()
>>>
>>>
>>> data = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'birthdate': date(1969, 7, 21),
... }
>>>
>>> json.dumps(data, cls=MyEncoder)
'{"firstname": "Mark", "lastname": "Watney", "birthdate": "1969-07-21"}'

4.5.6. 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 Composition A
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3

# %% English
# 1. Define class `UserPermissions`
# 2. Define class `AdminPermissions`
# 3. Compose `Account` from `UserPermissions`, `AdminPermissions`
# 4. Use composition
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj klasę `UserPermissions`
# 2. Zdefiniuj klasę `AdminPermissions`
# 3. Skomponuj `Account` z klas `UserPermissions`, `AdminPermissions`
# 4. Użyj kompozycji
# 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(UserPermissions)
>>> assert isclass(AdminPermissions)
>>> assert isclass(Account)

>>> result = Account()
Traceback (most recent call last):
TypeError: Account.__init__() missing 1 required positional argument: 'permissions'

>>> result = Account(UserPermissions())
>>> assert hasattr(result, 'permissions'), \
'Account instance must have `permissions` attribute'
>>> assert type(result.permissions) is UserPermissions

>>> result = Account(AdminPermissions())
>>> assert hasattr(result, 'permissions'), \
'Account instance must have `permissions` attribute'
>>> assert type(result.permissions) is AdminPermissions
"""


# Define class `UserPermissions`
# Define class `AdminPermissions`
# Compose `Account` from `UserPermissions`, `AdminPermissions`
# Use composition
# type: type[Account]
...