Message395541
I'm trying to think of an example, and what I've thought of so far is having a base dataclass that has a `__post_init__` method, and another dataclass that inherits from it and also has a `__post_init__` method.
In that case, the subclass might need to call `super().__post_init__()` inside its own `__post_init__` method, because otherwise, that wouldn't get called automatically.
Something along those lines:
>>> from dataclasses import dataclass, field
>>>
>>> @dataclass
... class A:
... x: int
... y: int
... xy: int = field(init=False)
...
... def __post_init__(self) -> None:
... self.xy = self.x * self.y
...
>>> @dataclass
... class B(A):
... m: int
... n: int
... mn: int = field(init=False)
...
... def __post_init__(self) -> None:
... super().__post_init__()
... self.mn = self.m * self.n
...
>>> b = B(x=2, y=4, m=3, n=6)
>>> b
B(x=2, y=4, xy=8, m=3, n=6, mn=18)
In this example, if not for the `super().__post_init__()` call inside B's `__post_init__`, we'd get an error `AttributeError: 'B' object has no attribute 'xy'`.
I believe this could be an actual pattern that could be used when dealing with dataclasses. |
|
Date |
User |
Action |
Args |
2021-06-10 15:11:05 | MicaelJarniac | set | recipients:
+ MicaelJarniac, eric.smith, docs@python |
2021-06-10 15:11:05 | MicaelJarniac | set | messageid: <1623337865.78.0.504082678731.issue44365@roundup.psfhosted.org> |
2021-06-10 15:11:05 | MicaelJarniac | link | issue44365 messages |
2021-06-10 15:11:05 | MicaelJarniac | create | |
|