简体   繁体   中英

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 xy )

Thanks for the help !

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.

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)

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.

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