以下产生 NameError: name 'Client' is not defined
。我该如何解决?
class Server():
def register_client(self, client: Client)
pass
class Client():
def __init__(self, server: Server):
server.register_client(self)
最佳答案
您可以使用 forward reference通过为尚未定义的 Client
类使用 string 名称:
class Server():
def register_client(self, client: 'Client')
pass
As of Python 3.7 ,您还可以通过在模块顶部添加以下 __future__
导入来推迟注释的 all 运行时解析:
from __future__ import annotations
此时注释被存储为表达式的抽象语法树的字符串表示;您可以使用 typing.get_type_hints()
解决这些问题(并解决上面使用的前向引用)。
见 PEP 563 -- Postponed Evaluation of Annotations详情;此行为将是 Python 4.0 中的默认行为。
关于python - 类型提示 : solve circular dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837918/