diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2021-05-10 13:38:46 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-05-10 13:38:46 (GMT) |
commit | f47305aa1fa41c38f744e9a16ae33b74c6fd45e7 (patch) | |
tree | 89f8c62fee01395cff2705861825e75734cb7f50 /Doc/library | |
parent | 9a0e65c8e05fdcd2207650d216ebdacdf0a025e9 (diff) | |
download | cpython-f47305aa1fa41c38f744e9a16ae33b74c6fd45e7.zip cpython-f47305aa1fa41c38f744e9a16ae33b74c6fd45e7.tar.gz cpython-f47305aa1fa41c38f744e9a16ae33b74c6fd45e7.tar.bz2 |
bpo-43558: Add note about base class initialization to dataclasses doc (GH-25967) (GH-26018)
(cherry picked from commit 2a031723eefcf6f1d678bbb4f6018610d43623c4)
Co-authored-by: dhoekstra2000 <douwe.hoekstra2512@gmail.com>
Co-authored-by: dhoekstra2000 <douwe.hoekstra2512@gmail.com>
Diffstat (limited to 'Doc/library')
-rw-r--r-- | Doc/library/dataclasses.rst | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index bfba15e..e203a1a 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -491,6 +491,27 @@ depend on one or more other fields. For example:: def __post_init__(self): self.c = self.a + self.b +The :meth:`__init__` method generated by :func:`dataclass` does not call base +class :meth:`__init__` methods. If the base class has an :meth:`__init__` method +that has to be called, it is common to call this method in a +:meth:`__post_init__` method:: + + @dataclass + class Rectangle: + height: float + width: float + + @dataclass + class Square(Rectangle): + side: float + + def __post_init__(self): + super().__init__(self.side, self.side) + +Note, however, that in general the dataclass-generated :meth:`__init__` methods +don't need to be called, since the derived dataclass will take care of +initializing all fields of any base class that is a dataclass itself. + See the section below on init-only variables for ways to pass parameters to :meth:`__post_init__`. Also see the warning about how :func:`replace` handles ``init=False`` fields. |