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

问题描述 投票:1回答:1

我有一个定义方法Baseeggs_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):
        # ...
python
1个回答
2
投票

您需要(很好,应该)复制它们;至少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.fooeggs参数提供类型提示。

$ 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)
© www.soinside.com 2019 - 2024. All rights reserved.