我是否需要为覆盖“@abstractmethod”的方法提供类型提示?

Do I need to provide type hints for methods overriding `@abstractmethod`s?

鉴于这两个 类:

class MyClass(ABC):
    @abstractmethod
    def my_method(self, my_parameter: str):
        pass
    
class MySecondClass(MyClass):
    def my_method(self, my_parameter): 
        pass

MySecondClassmy_method 中的 my_parameter 是否有基于 PEP 484Anystr 的推断类型?我在链接文档中找不到详细说明上述内容的示例。

Any。你可以通过 运行 mypy:

试试看
from abc import ABC, abstractmethod

class MyClass(ABC):
    @abstractmethod
    def my_method(self, my_parameter: str):
        pass
    
class MySecondClass(MyClass):
    def my_method(self, my_parameter):
        reveal_type(my_parameter)
        pass

MySecondClass().my_method(3)

With or without the --check-untyped-defs flag, this passes type checking, and reveal_typeAny 报告为类型。 (没有标志,方法体的类型检查也会被跳过。)


请注意,即使使用注释,也允许重写方法具有与被重写方法不同的签名,只要重写方法的签名更宽松即可。例如,采用 Animal 的方法可以覆盖采用 Dog.

的方法