简体   繁体   中英

Pythonic way to update multiple class variables in a loop?

I would like to update class variables with similar names in a loop:

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"

You can use the setattr function:

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

Use setattr to set the object's attribute value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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