猿问

输入提示:解决循环依赖

输入提示:解决循环依赖

以下产生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)


明月笑刀无情
浏览 591回答 2
2回答

阿晨1998

您可以通过使用尚未定义的类的字符串名称来使用转发引用:Clientclass 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中的默认行为。
随时随地看视频慕课网APP

相关分类

Python
我要回答