[英]How to change the value of a module variable from within an object of another module?
簡介 :我有一個腳本暴露(1)一個dict
,我需要從另一個模塊修改這個dict
注意 :對類似問題的兩個很好的答案解釋了很多關於模塊之間的變量范圍,但我不明白這是如何適用於我的情況。
在下面的代碼中,我預計我將能夠從submodule.py
修改mainmodule.py
變量container
,但實際情況並非如此。 為什么?
我應該如何從submodule
解決container
的mainmodule
實例?
主腳本的代碼
# mainmodule.py
# the main script which ultimately exposes the module variable 'container'
import submodule
container = dict()
class MainClass:
def __init__(self):
self.sub = submodule.SubClass()
def set(self, number):
print("main: container was {container}".format(container=container))
container['x'] = number
print("main: container is {container}".format(container=container))
def call(self, number):
self.sub.set(number)
if __name__ == "__main__":
mc = MainClass()
# updating container from this script
mc.set(1)
# updating container from another module
mc.call(2)
# again from this script, to check the updates
mc.set(3)
導入模塊的代碼
# submodule.py
import mainmodule
class SubClass:
def __init__(self):
pass
def set(self, number):
print("sub: container was {container}".format(container=mainmodule.container))
mainmodule.container['x'] = number
print("sub: container is {container}".format(container=mainmodule.container))
輸出是
main: container was {}
main: container is {'x': 1}
sub: container was {}
sub: container is {'x': 2}
main: container was {'x': 1}
main: container is {'x': 3}
(1)實際代碼使用bottle
通過json.dumps()
提供container
盯着你的代碼,我想我知道什么可能會讓你失望。 作為python foo.py
調用的python腳本最終將成為一個名為__main__
的模塊(在sys.modules
)。 這意味着你的mainmodule.py
節目的底mainmodule.py
被加載和編譯並運行一次,使用__name__ == "__main__"
,這會導致一些事情發生。 該模塊導入尚未導入的submodule
,以便加載和運行。
submodule
依次嘗試導入mainmodule
。 雖然之前已經執行過該文件,但解釋器並不知道該模塊名稱,因此mainmodule.py
再次運行,這次使用__name__ == "mainmodule"
(與"__main__"
,所以if
跳過底部的套件)。
這意味着你有兩個 container
副本,一個在模塊中,其名稱是__main__
,另一個在名為mainmodule
的模塊中。 兩者都來自名為./mainmodule.py
的文件這一事實並不重要。
有幾種方法可以解決這個問題。 一種是立即導入真實的,如:
# mainmodule.py
import submodule
class Foo:
pass
if __name__ == "__main__":
import mainmodule
mainmodule.Foo()
另一種選擇是將if
的代碼移動到另一個文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.