【问题标题】:Type-Hinting Child class returning self返回自我的类型提示子类
【发布时间】:2020-03-18 00:59:26
【问题描述】:

有没有办法输入一个抽象的父类方法,使得子类方法知道返回自己,而不是抽象父类。

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 的自动完成功能。

【问题讨论】:

  • @MadPhysicist 与此处无关,abstractmethods 需要使用pass...
  • @juanpa.arrivillaga。哇。当我读到通行证时,我忘记了那部分。我想这周该睡觉了。

标签: python abstract-class type-hinting abc


【解决方案1】:

因此,文档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 目前有一个警告:

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

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2023-02-19
    • 2015-11-23
    • 2021-05-29
    • 2016-12-28
    • 2015-03-09
    • 2021-10-15
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多