在 Python 中以编程方式创建变量 [英] Programmatically creating variables in Python
问题描述
可能的重复:
如何以编程方式设置全局(模块)变量?
我有一个名为 Variable 的类定义如下:
I have a class called Variable defined as so:
class Variable():
def __init__(self, name):
self.name = name
self._value = None
def value(self):
return self._value
def __repr__(self):
return self.name
我想像这样创建 26 个大写的单字母 Variable 实例:
I want to create 26 capital single letter instances of Variable like this:
A = Variable('A')
B = Variable('B')
...
Z = Variable('Z')
到目前为止,我已经尝试了各种解决方案,我想到的最好的是:
So far I've tried various solutions, and the best I've come up with is:
from string import uppercase
for char in uppercase:
exec "%s = %s" % (char, Variable(str(char))) in None
但是,这不会运行并给我这个错误:
However, this doesn't run and gives me this error:
Traceback (most recent call last):
File "C:\Users\Administrator\Dev\python\truthtable\truthtable.py", line 7, in <module>
exec "%s = %s" % (char, Variable(str(char))) in None
File "<string>", line 1, in <module>
NameError: name 'A' is not defined
我做错了什么?
推荐答案
from string import uppercase
_g = globals()
for char in uppercase:
_g[char] = Variable(char)
这是否是一个好想法仍然值得怀疑:)
Whether this is a good idea remains questionable :)
这仅适用于 globals()
(即模块级赋值),因为语言定义明确指出修改 locals()
返回的字典实际上可能不会改变任何局部变量的值.
This only works for globals()
(i.e. module level assignments), as the language definition explicitly states that modifying the dictionary returned by locals()
may not actually change the value of any local variables.
您也可以对类或实例的 __dict__
执行类似的操作.
You can also do something similar with the __dict__
of a class or instance.
这篇关于在 Python 中以编程方式创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!