我在使用 pycharm 编码时使用 python 的类型提示系统,我相信它使用 typing
模块,但是我有一个场景,pycharm 给我一个错误,并且我找不到回答如何使其正确在线:
from typing import List
class Something:
class A(object):
def __init__(self, d: int) -> None:
self.data = d
class B(object):
def __init__(self, inListStr: List[str], inListA: List[A]): # "A" here is marked as "Unresolved Reference". Something.A does not fix the issue either
self.list_of_str = inListStr
self.list_of_a = inListA
def __init__(self, inB: B): #B here is accepted ok
self.data_b = inB
你知道我如何正确地将 inListA
输入为“list of As”类型吗?
最佳答案
使用Something.A
,但将其括在引号中:
...
def __init__(self, inListStr: List[str], inListA: List['Something.A']):
...
Python 解释器无法在代码中的该点计算 A
或 Something.A
。通过将其设置为字符串,类型检查器仍然可以确定类型,同时避免运行时评估。
关于python - 在类构造函数中表达兄弟嵌套类的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67113582/