Kyle U
Kyle U

Reputation: 305

How to dynamically access/overwrite a field in a class using a variable?

I have a class where I would like to overwrite one instance with another (with the exception of one field). My approach was something along the lines of this:

for key in my_class_instance_1.__dict__.keys():
    if key != "key_i_dont_want_to_overwrite":
        my_class_instance_1[key] = my_class_instance_2[key]

The problem is that I get the error TypeError: 'MyClass' object is not subscriptable.

I am also apparently unable to access the instance like this: my_class_instance_1.f"{key}".

I don't know how to dynamically access a key on a class for the purpose of overwriting it. I know that I can use getattr(my_class_instance_2, key) in order to access the value, but this will not help me overwrite the value on my_class_instance_1.

Upvotes: 4

Views: 681

Answers (1)

Kyle U
Kyle U

Reputation: 305

Thanks to @kindall's and @skullgoblet1089's responses I was able to figure this out, but for anyone else that has this problem, let me show you the working code:

for key in my_class_instance_1.__dict__.keys():
    if key != "key_i_dont_want_to_overwrite":
        val = getattr(my_class_instance_2, key)  # the new value
        setattr(my_class_instance_1, key, val)  # overwriting the old value

There is a sibling function to getattr() called setattr() which allows you to set an attribute.

Upvotes: 4

Related Questions