我有一个定义方法eggs_or_ham的Base类。
我需要在我的子类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):
# ...发布于 2020-02-24 23:45:35
您需要(好吧,应该)复制它们;至少,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)https://stackoverflow.com/questions/60379309
复制相似问题