如何在python中正确地执行以下操作?
class AnyType: def __init__(self, Type:Union[PrimitiveType, ComplexType]): self.Type = Type class PrimitiveType(AnyType): def __init__(self, Type): super().__init__(Type) class NestedType(AnyType): def __init__(self, Type): super().__init__(Type)
NameError:未定义名称“PrimitiveType”
我知道C中有一个正向声明,但我如何防止python中出现以下循环引用?
有一个 PEP 描述这样的特征。如果你使用python3.7+,你可以添加 from __future__ import annotations 在开始时,它应该可以工作。在其他情况下,使用字符串可以解决问题
from __future__ import annotations
class AnyType: def __init__(self, Type:Union["PrimitiveType", "ComplexType"]): self.Type = Type