[英]How to specify the return type of parent method as the child class dynamically using python type hinting?
我想知道如果我想要 IDE 自動提示子方法該怎么辦? 以下代碼在 Pycharm 2019.2 中不起作用
我只能在父 class 中添加類型提示,但“最終類型”應在子 class 中動態確定
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.