bpo-43558: Add note about base class initialization to dataclasses doc (GH-25967)

This commit is contained in:
dhoekstra2000 2021-05-10 15:30:22 +02:00 committed by GitHub
parent 45862f9f5e
commit 2a031723ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 0 deletions

View File

@ -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.

View File

@ -736,6 +736,7 @@ David Hobley
Tim Hochberg
Benjamin Hodgson
Joerg-Cyril Hoehle
Douwe Hoekstra
Gregor Hoffleit
Chris Hoffman
Tim Hoffmann

View File

@ -0,0 +1,2 @@
Add the remark to :mod:`dataclasses` documentation that the :meth:`__init__` of any base class
has to be called in :meth:`__post_init__`, along with a code example.