<p>问题(很可能)与<code>dataclass</code>无关。问题在于Python的<a href="http://python-history.blogspot.com/2010/06/method-resolution-order.html" rel="nofollow noreferrer">method resolution</a>。在<code>super()</code>上调用方法调用<a href="https://www.python.org/download/releases/2.3/mro/" rel="nofollow noreferrer">MRO</a>链中父类中找到的第一个方法。因此,要使其正常工作,您需要手动调用父类的方法:</p>
<pre><code>@dataclass
class NamedAndNumbered(NumberedObj, NamedObj):
def __post_init__(self):
NamedObj.__post_init__(self)
NumberedObj.__post_init__(self)
print("NamedAndNumbered __post_init__")
</code></pre>
<p>另一种方法(如果您真的喜欢<code>super()</code>)是通过在所有父类中调用<code>super()</code>来继续MRO链(但它需要在链中有一个<code>__post_init__</code>):</p>
<pre><code>@dataclass
class MixinObj:
def __post_init__(self):
pass
@dataclass
class NamedObj(MixinObj):
name: str
def __post_init__(self):
super().__post_init__()
print("NamedObj __post_init__")
self.name = "Name: " + self.name
@dataclass
class NumberedObj(MixinObj):
number: int = 0
def __post_init__(self):
super().__post_init__()
print("NumberedObj __post_init__")
self.number += 1
@dataclass
class NamedAndNumbered(NumberedObj, NamedObj):
def __post_init__(self):
super().__post_init__()
print("NamedAndNumbered __post_init__")
</code></pre>
<p>在这两种方法中:</p>
<pre><code>>>> nandn = NamedAndNumbered('n_and_n')
NamedObj __post_init__
NumberedObj __post_init__
NamedAndNumbered __post_init__
>>> print(nandn.name)
Name: n_and_n
>>> print(nandn.number)
1
</code></pre>