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
“作为列表”的类型吗?
解决方案
使用Something.A
,但用引号括起来:
...
def __init__(self, inListStr: List[str], inListA: List['Something.A']):
...
Python 解释器无法评估A
或Something.A
在代码中的那个点。通过将其设为字符串,类型检查器仍然可以在避免运行时评估的同时找出类型。
推荐阅读
- android - 如何使用 gms.vision.CameraSource 进行缩放
- php - 关于Word Press中多重排序的问题
- javascript - 这个循环是什么?
- angular - 如何修复Angular应用程序中的标题
- c - 如何阻止字符串替换以前的元素?
- ffmpeg - FFMPEG 合并一个音频和一个视频文件
- oracle - SQL AUTO_INCREMENT 并将许多值插入一行
- sql - 显示具有来自不同表的匹配数据的 SQL 表记录
- javascript - 在 Three.js 中拉伸 2D 彩色图像
- azure - 将 Azure Web 应用程序移入新的 Azure 应用程序服务计划?