gpt4 book ai didi

python - 如何使用python类型提示动态地将父方法的返回类型指定为子类?

转载 作者:行者123 更新时间:2023-12-05 07:17:56 25 4
gpt4 key购买 nike

我想知道如果我想让 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

最佳答案

你是说

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

关于python - 如何使用python类型提示动态地将父方法的返回类型指定为子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com