Let's say I have a class with three attributes :
class Human:
name = 'Thomas'
age = 15
robot = False
I know I can access the attributes with the .attribute :
h = Human()
h.name # Thomas
h.age # 15
h.robot # False
However for some purposes I would like to modiy an attribute in a generic way :
def modify_attribute(object, attribute, new_value):
object.attribute = new_value
But python won't understand if I give modify_attribute(h, name, 'Juliette')
or modify_attribute(h, 'name', 'Juliette')
. In the latter case it compiles but it just doesn't change the name.
I read about getattr()
and thought I could get away with getattr(h, 'name') = 'Juliette'
however it appears this is not a valid expression. (I tried this because help(getattr)
says getattr(x, 'y')
is equivalent to x.y
)
Thanks for the help !
As mentioned above, you can achieve this by using setattr. i would give a sample code
>> class Person: ...
>> setattr(Person, 'age', 10)
>> print(Person.age)
10
However, it would violates principles in OOP as you would have to know too much details about the object to make sure that you won't break the internal behavior of the object after setting the new attribute.