我有一个奇怪的情况,添加显式类型提示似乎会使 mypy 失败。
此代码验证(Python 3.6.1,mypy 0.540):
class BaseA:
def __init__(self):
self.foo: float = 1.0
class DerivedA(BaseA):
@property
def foo(self):
return 2.0
但告诉 mypy 什么属性返回失败
class BaseB:
def __init__(self):
self.foo: float = 1.0
class DerivedB(BaseB):
@property
def foo(self) -> float:
return 2.0
# error: Signature of "foo" incompatible with supertype "BaseB"
相关的,我认为,离开注释也会因多重继承而失败,无论哪种组合(两者,任一,无)都被注释:
class BaseC:
foo: float = 1.0
class MixinC:
@property
def foo(self):
return 2.0
class DerivedC(MixinC, BaseC):
pass
# error: Definition of "foo" in base class "MixinC" is incompatible with
# definition in base class "BaseC"
任何想法为什么,或者如何改变?