python - 我需要在子类中复制我的类型注释吗?
问题描述
我有一个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)
推荐阅读
- javascript - 如何使用 express 在路由器中连续处理两个斜杠?
- fable-f# - HTML-to-Fable/Elmish 工具的输出是否也适用于 Giraffe 的 ViewEngine?
- javascript - 如何使用 IP 地理定位记录位置?
- r - 将行折叠成一个值
- javascript - 如何使用 JavaScript 语言创建的代码在我的 html 页面上显示投注计算器结果
- c++ - ESP32 | 如何将字符串分配给 char 指针?
- r - 如何从 2004 Wayback 机器站点上抓取此文本/为什么我运行错误的代码?
- asp.net-mvc - 如何减去两个日期并以分钟为单位转换新日期?
- javascript - 如何更改嵌套/递归 JSON 的结构
- flutter - 如何在颤振中改变状态?