gpt4 book ai didi

python - 类型提示 : solve circular dependency

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:23 25 4
gpt4 key购买 nike

以下内容会产生NameError:名称“Client”未定义。怎么解决呢?

class Server:
def register_client(self, client: Client)
pass


class Client:
def __init__(self, server: Server):
server.register_client(self)

最佳答案

您可以使用 forward reference通过使用尚未定义的 Client 类的字符串名称:

class Server:
def register_client(self, client: 'Client')
pass

As of Python 3.7 ,您还可以通过在模块顶部添加以下 __future__ 导入来推迟注释的所有运行时解析:

from __future__ import annotations

此时注释被存储为表达式的抽象语法树的字符串表示形式;您可以使用typing.get_type_hints()解决这些问题(并解决上面使用的前向引用)。

参见PEP 563 -- Postponed Evaluation of Annotations了解详情。

关于python - 类型提示 : solve circular dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56572068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com