簡體   English   中英

從另一個模塊更改的訪問變量

[英]Access variable that was changed from another module

我正在研究Python並創建一個簡單的聊天機器人。 考慮我有一個具有主要功能的模塊:

# bot.py
class QueueWrapper:
    pass

wrapper = QueueWrapper() # also tried with dict

def main():
    wrapper.queue = init_queue()

if __name__ == '__main__':
    main()

並考慮有另一個模塊,我想從bot模塊訪問queue ,但是在bot.py模塊被調用一段時間后,該模塊的函數被調用:

# another_module.py
from bot import wrapper

def create_job():
    wrapper.queue.do_smth() # <- error. object has no attribute ...

當我嘗試訪問應該在wrapper對象中的queue ,出現錯誤,並指出wrapper沒有queue 但是,如果我在bot模塊上以調試模式運行,則可以清楚地看到wrapper.queue包含對象。 但是,當從another_module.py調用create_job函數時,它不知道wrapper中有一個queue

在我看來,這里的問題是來自bot.py var queuemain()init_queue()完成工作之后被初始化,但是模塊本身在此之前被導入了another_module

我在做什么錯(可能缺少有關變量作用域的信息),如何在調用create_job()時初始化我的wrapper.queue

提前致謝!

您可以使用屬性 ,以便queue屬性在首次訪問時自動初始化:

class QueueWrapper:
    _queue = None

    @property
    def queue(self):
        if self._queue is None:
            self._queue = init_queue()
        return self._queue

wrapper = QueueWrapper()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM