类型提示子类返回

2024-04-19 08:43:20 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有任何方法可以键入抽象父类方法,使子类方法返回自身,而不是抽象父类方法。你知道吗

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

这更多是为了改进像PyCharm或VScode的python插件这样的ide的自动完成功能。你知道吗


Tags: 方法self键入defpass子类whatmethod
1条回答
网友
1楼 · 发布于 2024-04-19 08:43:20

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

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())

mypy给了我们:

test_typing.py:22: note: Revealed type is 'test_typing.Child1*'
test_typing.py:23: note: Revealed type is 'test_typing.GrandChild1*'

注意,我必须一直使用类型变量来实现这一点,所以当我最初尝试在子类注释中使用实际的子类时,它(错误地?)继承了孙子中的类型:

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

我要和mypy谈谈:

test_typing.py:22: note: Revealed type is 'test_typing.Child1'
test_typing.py:23: note: Revealed type is 'test_typing.Child1'

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

This feature is experimental. Checking code with type annotations for self arguments is still not fully implemented. Mypy may disallow valid code or allow unsafe code.

相关问题 更多 >