我有一个定义方法Base
的eggs_or_ham
类。
我是否需要在我的子类Foobar
中复制类型注释,或者足以将它们添加到Base
类中?
class Base:
# ...
@classmethod
def eggs_or_ham(cls, eggs: List[Egg], ham: List[Ham]) -> List[str]:
raise NotImplementedError
class Foobar(Base):
# should I write this
@classmethod
def eggs_or_ham(cls, eggs: List[Egg], ham: List[Ham]) -> List[str]:
# ...
# or this
@classmethod
def eggs_or_ham(cls, eggs, ham):
# ...
您需要(很好,应该)复制它们;至少mypy
不“继承”类型提示。
给出一个简单的例子
from typing import List
class Base:
@classmethod
def foo(cls, eggs: List[str]) -> List[str]:
return ["base"]
class Foo(Base):
@classmethod
def foo(cls, eggs) -> List[str]:
return ["foo"]
print(Foo.foo([1,2,3]))
将进行类型检查,因为没有为Foo.foo
的eggs
参数提供类型提示。
$ mypy tmp.py
Success: no issues found in 1 source file
[添加类型提示(eggs: List[str]
)会产生预期的错误:
$ mypy tmp.py
tmp.py:15: error: List item 0 has incompatible type "int"; expected "str"
tmp.py:15: error: List item 1 has incompatible type "int"; expected "str"
tmp.py:15: error: List item 2 has incompatible type "int"; expected "str"
Found 3 errors in 1 file (checked 1 source file)