'modify attribute with getattr - is it possible?
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 !
Solution 1:[1]
In answer to your specific question: no, you can't use getattr
to replace an attribute (which is what your example is trying to do). You can use it to get an attribute that, if mutable, can be modified.
Solution 2:[2]
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.
Solution 3:[3]
Thanks to @Scott Hunter & @Richard Neumann who solved it in the comments section.
If you want to set, not get the attribute, use
setattr()
:setattr(object, attribute, new_value)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Scott Hunter |
Solution 2 | racey chan |
Solution 3 | richardec |