如何在循环中重新分配对象?

时间:2019-08-21 10:12:08

标签: python python-3.x python-2.7

[当前代码]:

a = table.a
b = table.b
c = table.c

[预期输出]

all = [a, b, c]
for i in all:
 i = table.i

3 个答案:

答案 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)

如果这段代码不在函数内部(或者,如果在函数内部但abc在该函数之外的其他任何地方都不需要)通过更新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


只需了解一下后果:如果在该范围内还有其他变量abc(因为变量名不正确,就不应该存在),它们将被覆盖。

答案 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']