首页 > 解决方案 > 我需要在子类中复制我的类型注释吗?

问题描述

我有一个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):
        # ...

标签: python

解决方案


您需要(嗯,应该)复制它们;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)

推荐阅读