简体   繁体   English

在循环中更新多个 class 变量的 Pythonic 方法?

[英]Pythonic way to update multiple class variables in a loop?

I would like to update class variables with similar names in a loop:我想在循环中更新具有相似名称的 class 变量:

I have the following code:我有以下代码:

class Table:
    def __init__(self):
        pass

    acc_counter = 0
    acc0 = 0
    acc1 = 0
    acc2 = 0
    acc3 = 0
    acc4 = 0

I could update each value manually:我可以手动更新每个值:

Table.acc0 = 0
Table.acc1 = 1
Table.acc2 = 2
Table.acc3 = 3
Table.acc4 = 4

However, I'm wondering if I could do it in a loop, something like that:但是,我想知道是否可以循环执行,例如:

for i in range(5):
    print(getattr(Table, f"acc{i}"))
    #getattr(Table, f"acc{i}") = i

If the last line of the code is uncommented it returns: "SyntaxError: can't assign to function call"如果代码的最后一行未注释,则返回:“SyntaxError: can't assign to function call”

You can use the setattr function:您可以使用setattr function:

for i in range(5):
    setattr(Table, f"acc{i}", i)

Use setattr to set the object's attribute value使用setattr设置对象的属性值

for i in range(5):
    print(getattr(Table, f"acc{i}"))
    setattr(Table, f"acc{i}", i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM