首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我需要在子类中复制我的类型注解吗?

我需要在子类中复制我的类型注解吗?
EN

Stack Overflow用户
提问于 2020-02-24 23:39:07
回答 1查看 37关注 0票数 1

我有一个定义方法eggs_or_hamBase类。

我需要在我的子类Foobar中复制类型注释吗?或者在Base类中拥有它们就足够了吗?

代码语言:javascript
复制
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):
        # ...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-24 23:45:35

您需要(好吧,应该)复制它们;至少,mypy不会“继承”类型提示。

给出一个更简单的例子,

代码语言:javascript
复制
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.fooeggs参数提供类型提示。

代码语言:javascript
复制
$ mypy tmp.py
Success: no issues found in 1 source file

添加回类型提示(eggs: List[str])会产生预期的错误:

代码语言:javascript
复制
$ 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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60379309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档