Python中通常不做严格的类型定义,但如果是罕用且固定的数据结构,还是定义分明应用起来更不便(起码对象前面打.的时候,IDE能够主动给出办法和属性名提醒)。这时,一个简单的构造,就有可能循环援用,比方:
from typing import Listclass A: x: str y: Bclass B: w: List[A]
这样的代码,连编译都过不去,会在‘y: B’,这个地位,间接提醒:‘Unresolved reference B’。解决方案有两个:
- 放弃在同一个文件中定义类
此时能够增加一个非凡的援用:from __future__ import annotations
,告知编译器先“通读”整个文件,再解决typing annotation,就能够防止上述问题。 - 拆分到不同模块中
这种状况下,就得在援用另外一个类的时候,间接援用它的模块,而不是类名:
Module1.py
from . import Module2class A: x: str y: Module2.B
Module2.py
from typing import Listfrom . import Module1class B: w: List[Module1.A]