当我创建一个扩展__init__
逻辑的mixin类时,通常要做的是:
class ExtraValuemixin:
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# some extra initialization
self._extra_value = 1
def retrieve_extra_value(self):
return self._extra_value
但是,对于mypy来说,这似乎是错误的,
Too many arguments for "__init__" of "object"
我明白了,*args
的构造函数签名中没有**kwargs
或object
;但这是一个mixin,它依赖于其子级的构造函数。我该如何让mypy理解这一点?
完整示例:
class ExtraValuemixin:
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# some extra initialization
self._extra_value = 1
def retrieve_extra_value(self):
return self._extra_value
class ParentObj:
def __init__(self, value):
self.value = value
class ChildObj(ExtraValuemixin, ParentObj):
pass
obj = ChildObj(value=5)
print(obj.retrieve_extra_value())