python - 在类构造函数中表达兄弟嵌套类的类型提示

标签 python type-hinting python-typing

我在使用 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 解释器无法在代码中的该点计算 ASomething.A。通过将其设置为字符串,类型检查器仍然可以确定类型,同时避免运行时评估。

关于python - 在类构造函数中表达兄弟嵌套类的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67113582/

相关文章:

python - python 类型注释中的链式引用

Python 3 基类类型注解只允许当前子类

python - 如何检查具体方法是否遵守抽象方法的类型提示

python-3.x - 在 Union 中处理带有值的参数的 Pythonic 方法

python - 在 python 中,如何输入提示不是 str 或 bytes 而是序列的输入?

python - 我应该将列表子类化还是使用列表作为属性创建类?

python - 将错误栏添加到 Matplotlib 生成的 Pandas 数据框图形会创建无效图例

python - Polars API 注册和类型检查器

python - 获取矩形 mask 的真实边界框

python - 在仅容器开发环境之外运行 django `makemigrations` 的正确做法是什么