[英]Incompatible types in assignment in inheritance - Mypy error
在我的项目中,我的 Mypy 困扰着我一些 inheritance,我找不到在某些情况下它不抱怨错误的原因:
note: In class "Cat":
Incompatible types in assignment (expression has type "Dict[str, Any]", base class "Animal" defined the type as "None")
并且不适用于Dog
,代码示例:
class Animal:
attributes = None
def __init__(self):
if attributes is None:
raise NotImplementedExcepton
class Cat(Animal):
attributes = {
'fur': 'black',
'sound': 'meow',
}
class Dog(Animal):
attributes = {
'fur': 'brown',
'sound': 'woof',
}
attributes
可以是None
,如Animal
中所示,因此您将其定义为Optional
。 然后,您还定义了可能的attributes
类型。
from typing import Dict, Optional
class Animal:
attributes: Optional[Dict[str, str]] = None
def __init__(self):
if self.attributes is None:
raise Exception
class Cat(Animal):
attributes = {
'fur': 'black',
'sound': 'meow',
}
这不会引发任何 mypy 错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.