【问题标题】:How to specify the return type of parent method as the child class dynamically using python type hinting?如何使用python类型提示动态地将父方法的返回类型指定为子类?
【发布时间】:2020-02-23 11:20:53
【问题描述】:

我想知道如果我想让 IDE 自动提示子方法该怎么办?以下代码在 Pycharm 2019.2 中不起作用

我只能在父类中添加类型提示,但“最终类型”应该在子类中动态确定

from typing import TypeVar, List

T = TypeVar("T")


class Node:
    def __init__(self: T, neighbours: List[T]):
        self.neighbours = neighbours # The "final type" should be determined dynamically

    def get_neighbours(self) -> List[T]:
        return self.neighbours


class ChildNodeA(Node):
    def child_method_a(self):
        pass

class ChildNodeB(Node):
    def child_method_b(self):
        pass

class ChildNodeC(Node):
    def child_method_c(self):
        pass


child_node = ChildNodeA([])

for node in child_node.neighbours:
    node.child_method_a() # I want the pycharm to auto-hint child_method_a 

child_node = ChildNodeB([])
for node in child_node.neighbours:
    node.child_method_b() # I want the pycharm to auto-hint child_method_b

【问题讨论】:

  • 不确定我是否正确理解了您的要求,但为了让 PyC​​harm 显示自动完成的 ChildNodeNode 方法,您只需要前向引用:List['ChildNode']。请注意,该类是通过其名称引用的,即作为字符串。
  • 或者,在 Python 3.7+ 中,您可以使用__future__ 中的annotations,正如this question 的已接受答案中很好解释的那样(这可能是一个欺骗目标)。
  • @shmee 谢谢你的回复。我没有很好地表达我的要求,我修改了我的问题。问题是我只能在父类中添加类型提示,但“最终类型”应该在子类中动态确定

标签: python type-hinting


【解决方案1】:

你是说

class ChildNode(Node):
    def child_method(self) -> str:
        return 'test'

【讨论】:

  • 我没有很好地表达我的要求,我修改了我的问题。问题是我只能在父类中添加类型提示,但“最终类型”应该在子类中动态确定
猜你喜欢
  • 1970-01-01
  • 2017-01-18
  • 2016-02-29
  • 2016-08-17
  • 2020-05-26
  • 1970-01-01
  • 2023-03-29
  • 2016-09-10
  • 1970-01-01
相关资源
最近更新 更多