输入提示:解决循环依赖以下产生NameError: name 'Client' is not defined。我该如何解决?class Server():
def register_client(self, client: Client)
passclass Client():
def __init__(self, server: Server):
server.register_client(self)
2 回答

阿晨1998
TA贡献2037条经验 获得超6个赞
您可以通过使用尚未定义的类的字符串名称来使用转发引用:Client
class Server(): def register_client(self, client: 'Client') pass
从Python 3.7开始,您还可以通过在模块顶部添加以下导入来推迟所有运行时解析注释__future__
:
from __future__ import annotations
此时,注释被存储为表达式的抽象语法树的字符串表示; 您可以使用它typing.get_type_hints()
来解决这些问题(并解决上面使用的前向引用)。
有关详细信息,请参阅PEP 563 - 延迟评注注释 ; 此行为将是Python 4.0中的默认行为。
添加回答
举报
0/150
提交
取消