4.3. Dataclass Relations¶
4.3.1. SetUp¶
>>> from dataclasses import dataclass
>>> from typing import Self
4.3.2. Relation to Objects¶
>>> @dataclass
... class Group:
... gid: int
... name: str
>>>
>>>
>>> @dataclass
... class User:
... firstname: str
... lastname: str
... groups: list[Group]
Usage:
>>> mark = User('Mark', 'Watney', groups=[
... Group(gid=1, name='users'),
... Group(gid=2, name='staff'),
... Group(gid=3, name='admins')])
4.3.3. Relation to Self¶
Note, that there are
None
default friendsUsing an empty list
[]
as a default value will not workSelf
is available since Python 3.11We will cover this topic later
Import:
>>> from typing import Self
Define class:
>>> @dataclass
... class User:
... firstname: str
... lastname: str
... friends: list[Self] = None
Use:
>>> mark = User('Mark', 'Watney', friends=[
... User('Melissa', 'Lewis'),
... User('Rick', 'Martinez'),
... User('Beth', 'Johanssen'),
... User('Chris', 'Beck'),
... User('Alex', 'Vogel')])