类型提示子类返回自我

dbo*_*ers 10 python abstract-class abc type-hinting

有没有办法输入抽象父类方法,以便知道子类方法返回自身,而不是抽象父类。

class Parent(ABC):
    @abstractmethod
    def method(self) -> [what to hint here]:
        pass

class Child1(Parent)
    def method(self):
        pass

    def other_method(self):
        pass

class GrandChild1(Child1)
    def other_method_2(self):
        pass
Run Code Online (Sandbox Code Playgroud)

这更多是为了改进 PyCharm 或 VScode 的 python 插件等 IDE 的自动完成功能。

jua*_*aga 8

因此,此处的文档中描述了一般方法

import typing
from abc import ABC, abstractmethod

T = typing.TypeVar('T', bound='Parent') # use string

class Parent(ABC):
    @abstractmethod
    def method(self: T) -> T:
        ...

class Child1(Parent):
    def method(self: T) -> T:
        return self

    def other_method(self):
        pass

class GrandChild1(Child1):
    def other_method_2(self):
        pass

reveal_type(Child1().method())
reveal_type(GrandChild1().method())
Run Code Online (Sandbox Code Playgroud)

mypy给我们:

test_typing.py:22: note: Revealed type is 'test_typing.Child1*'
test_typing.py:23: note: Revealed type is 'test_typing.GrandChild1*'
Run Code Online (Sandbox Code Playgroud)

请注意,我必须继续使用类型变量才能使其正常工作,因此当我最初尝试在子类注释中使用实际子类时,它(错误地?)继承了孙子类中的类型:

class Child1(Parent):
    def method(self) -> Child1:
        return self
Run Code Online (Sandbox Code Playgroud)

我会用 mypy:

test_typing.py:22: note: Revealed type is 'test_typing.Child1'
test_typing.py:23: note: Revealed type is 'test_typing.Child1'
Run Code Online (Sandbox Code Playgroud)

同样,我不确定这是否是预期/正确的行为。该mypy文档目前有一个警告:

此功能是实验性的。检查带有 self 参数的类型注释的代码仍未完全实现。Mypy 可能不允许有效代码或允许不安全代码。