[当前代码]:
a = table.a
b = table.b
c = table.c
[预期输出]
all = [a, b, c]
for i in all:
i = table.i
答案 0 :(得分:1)
我认为,使用dict作为动态变量的存储库,这更接近您的预期:
class Table(object):
def __init__(self):
self.a = None
self.b = None
self.c = None
self.d = None
self.e = None
table = Table()
table.a = 1
table.b = 2
table.c = 3
table.d = 4
table.e = 5
# copy only this variables
some_vars = ['a', 'b', 'c']
# this line does the trick
my_vars = { var: getattr(table, var) for var in some_vars }
现在,我们已在字典中将对象的属性捕获为键值对:
my_vars['a']
=> 1
my_vars['b']
=> 2
my_vars['c']
=> 3
答案 1 :(得分:1)
如果这段代码不在函数内部(或者,如果在函数内部但a
,b
和c
在该函数之外的其他任何地方都不需要)通过更新locals
字典,无需使用其他容器即可完成此操作:
attributes = ['a', 'b', 'c']
for attr in attributes:
locals()[attr] = getattr(table, attr)
例如:
table = type('table', (), {'a': 1})()
attributes = ['a']
for attr in attributes:
locals()[attr] = getattr(table, attr)
print(a)
输出
1
只需了解一下后果:如果在该范围内还有其他变量a
,b
和c
(因为变量名不正确,就不应该存在),它们将被覆盖。
答案 2 :(得分:0)
在i
中修改for i in all
不会更改all
的元素,但是您可以这样迭代:
class Table(object):
pass
table = Table()
table.a = 'AAA'
table.b = 'BBB'
table.c = 'CCC'
all = ['a', 'b', 'c']
for idx in range(len(all)):
all[idx] = getattr(table, all[idx])
print(all)
输出:
['AAA', 'BBB', 'CCC']