在类构造函数中表示同级嵌套类的类型提示

2024-10-03 15:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用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键入“As列表”类型吗


Tags: selftyping类型datahereobjectinitdef
1条回答
网友
1楼 · 发布于 2024-10-03 15:33:24

使用Something.A,但要用引号括起来:

...
        def __init__(self, inListStr: List[str], inListA: List['Something.A']):
...

Python解释器无法在代码中的该点计算ASomething.A。通过将其设置为字符串,类型检查器仍然可以找出类型,同时避免运行时计算

相关问题 更多 >