首页 > 解决方案 > 在类构造函数中表达同级嵌套类的类型提示

问题描述

我在使用 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“作为列表”的类型吗?

标签: pythontype-hintingpython-typing

解决方案


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

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

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


推荐阅读