簡體   English   中英

如何以編程方式設置全局(模塊)變量?

[英]How to programmatically set a global (module) variable?

我想以“程序化”的方式定義全局變量。 類似於我想做的事情將是:

definitions = {'a': 1, 'b': 2, 'c': 123.4}
for definition in definitions.items():
    exec("%s = %r" % definition)  # a = 1, etc.

具體來說,我想創建一個模塊fundamentalconstants ,其中包含可作為fundamentalconstants.electron_mass等訪問的變量,其中所有值都是通過解析文件獲得的(因此需要以“編程”方式進行賦值)。

現在,上面的exec解決方案可行。 但我對它有點不安,因為我擔心exec不是實現設置模塊全局變量的最簡潔方法。

這是一個更好的方法:

import sys
definitions = {'a': 1, 'b': 2, 'c': 123.4}
module = sys.modules[__name__]
for name, value in definitions.iteritems():
    setattr(module, name, value)

您可以在globals()返回的字典中設置全局變量:

definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
    globals()[name] = value

你是對的, exec通常是個壞主意,在這種情況下肯定不需要。

奈德的答案很好。 如果你是一個模塊,另一種可行的方法是自己導入:

fundamentalconstants.py:

import fundamentalconstants

fundamentalconstants.life_meaning= 42

for line in open('constants.dat'):
    name, _, value= line.partition(':')
    setattr(fundamentalconstants, name, value)

暫無
暫無

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

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