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