Skip to content
Advertisement

How to change the values of instance attributes in a loop

I have a work implantation of python which has some inbuilt dialog boxes so I cannot share the original code here. The problem I have is I want to update the values of some instance attributes. I made a dictionary from zipping 2 lists together so that in a for loop I could mention to the user the string that they need to see for what they are updating(the dictionary key), and the instance attribute I want to change is the value of in the dictionary. But all its doing is changing the dictionary value, not the instance attribute value.

The dialog box will ask users “do you want to change {x relayed name} in a json file?”. The value associated with that name in the dictionary is the instance attribute to be updated.

So I don’t know if it can be done. Anyone got any ideas if it can?

Updated question after good comments made it clear the question was miswritten.

Code

class MyClass:

    def __init__(self):
        self.x = 10.0
        self.y = 20.0

    def get_user_input(self):
        usr_ret = input("input a number :")
        return usr_ret


if __name__ == "__main__":
    m = MyClass()
    print(m.x)
    list_a = ["x_related_name", "y_related_name"]
    list_b = [m.x, m.y]
    mydict = dict(zip(list_a, list_b))
    for k, v in mydict.items():
        print(k, " : ", v)

    # update the class attribute value
    for k, v in mydict.items():

    
    #Can I update the class attributes x and y in a loop?

Advertisement

Answer

Would you want getattr and setattr? In the following, I simplified the example, as I can’t find where user inputs are used in your example.

getattr gets the attribute value according to the attribute name, and setattr sets a value to a specified attribute (again, based on its name). So you just need to store the attribute names in a list of strings, and the loop over the list as needed.

class MyClass:
    def __init__(self):
        self.x = 10.0
        self.y = 20.0

if __name__ == "__main__":
    m = MyClass()
    attrs = ['x', 'y']
    for a in attrs:
        print(f"{a}: {getattr(m, a)}")
    set_as = [42, 2021]
    for a, v in zip(attrs, set_as):
        setattr(m, a, v)
    for a in attrs:
        print(f"{a}: {getattr(m, a)}")
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement