Eric V. Smith <[email protected]> added the comment:
dataclasses doesn't know the signature of the base class's __init__, so it
can't know how to call it. I realize you've given an example that would accept
any parameters, but that isn't typical.
What if the base class was:
@dataclasses.dataclass
class Foo:
foo: int
def __init__(self, baz):
...
pass
What would the generated Bar.__init__() look like if it were calling the base
class __init__()? What would get passed to baz?
> So if a dataclass uses a custom __init__, all its child classes must also use
> a custom __init__
This isn't true. The typical way to handle this is for the derived class to add
a __post_init__() that calls into the base class's __init__(). This way, you
can use the normally generated __init__() in the derived class, yet still call
the base class's __init__() (which presumably you have some knowledge of). If
that doesn't work for some reason (for example, you strictly require that the
base class is initialized before the derived class, for some reason), then yes,
you'd need to write a custom __init__() in the derived class. dataclasses isn't
designed to handle every case: just the most common ones.
In your case, you could do:
@dataclasses.dataclass
class Bar(Foo):
bar: int
def __post_init__(self):
Foo.__init__(self, baz=self.bar) # or whatever
----------
nosy: +eric.smith
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue43835>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com