使用多重继承需要类通过在适当的地方调用它们的super() 方法来进行协作。就像__init__ 应该服从super().__init__,__post_init__ 应该服从super() .__post_init__。
由于dataclasses 没有公共基类,因此必须遵守super 方法; getattr 带有 no-op 功能,可以根据需要跳过 super 调用。
@dataclass
class A:
a: Dict[str, int] = field(default_factory=dict)
def __post_init__(self):
getattr(super(), "__post_init__", lambda: None)()
self.a = {'a1': 0, 'a2': 0}
def add_key_a(self, key):
self.a['key'] = 0
@dataclass
class B:
b: Dict[str, int] = field(default_factory=dict)
def __post_init__(self):
getattr(super(), "__post_init__", lambda: None)()
self.b = {'b1': 0, 'b2': 0}
def add_key_b(self, key):
self.b['key'] = 0
天真地,人们只会使用super().__post_init__() 来调用super 类的__post_init__。但是由于dataclass 通过代码生成而不是继承工作,超类是object——它没有__post_init__ 方法!因此,最终查找将失败:
>>> c = C()
>>> super(C, c).__post_init__ # initial __post_init__ used by C instances
<bound method A.__post_init__ of C(b={}, a={'a1': 0, 'a2': 0})>
>>> super(A, c).__post_init__ # second __post_init__ used by C
<bound method B.__post_init__ of C(b={}, a={'a1': 0, 'a2': 0})>
>>> super(B, c).__post_init__ # final __post_init__ used by C
...
AttributeError: 'super' object has no attribute '__post_init__'
解决这个问题的方法很简单:只要捕获AttributeError,如果它发生并且在这种情况下什么都不做。我们可以使用 try: except: 块来做到这一点,但有一种更简洁的方法。
The builtin getattr function 允许获取属性或默认值。代替a.b,我们可以使用getattr(a, "b", default)。由于我们要调用一个方法,因此一个有用的默认值是一个什么都不做的可调用对象。
>>> lambda : None # callable that does nothing
<function __main__.<lambda>()>
>>> # definition | call
>>> (lambda: None)() # calling does nothing
>>> # getattr fetches attribute/method...
>>> getattr(super(A, c), "__post_init__")
<bound method B.__post_init__ of C(b={}, a={'a1': 0, 'a2': 0})>
>>> # ... and can handle a default
>>> getattr(super(B, c), "__post_init__", lambda: None)
<function __main__.<lambda>()>
为此,我们将….__post_init__ 替换为getattr。值得注意的是,正如我们在….__post_init__ 查找之后需要() 一样,我们仍然需要() 来在getattr 查找之后进行调用。
super().__post_init__()
#super | method | call
# |super | | method | | default | | call
getattr(super(), "__post_init__", lambda: None)()