輸入提示:解決循環(huán)依賴以下產(chǎn)生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貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以通過使用尚未定義的類的字符串名稱來使用轉(zhuǎn)發(fā)引用:Client
class Server(): def register_client(self, client: 'Client') pass
從Python 3.7開始,您還可以通過在模塊頂部添加以下導(dǎo)入來推遲所有運(yùn)行時(shí)解析注釋__future__
:
from __future__ import annotations
此時(shí),注釋被存儲(chǔ)為表達(dá)式的抽象語法樹的字符串表示; 您可以使用它typing.get_type_hints()
來解決這些問題(并解決上面使用的前向引用)。
有關(guān)詳細(xì)信息,請(qǐng)參閱PEP 563 - 延遲評(píng)注注釋 ; 此行為將是Python 4.0中的默認(rèn)行為。
添加回答
舉報(bào)
0/150
提交
取消