简体   繁体   English

用 getattr 修改属性 - 有可能吗?

[英]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 :我知道我可以使用 .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') .但是如果我给modify_attribute(h, name, 'Juliette')modify_attribute(h, 'name', 'Juliette') python 将无法理解。 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.我阅读了有关getattr()的内容,并认为我可以摆脱getattr(h, 'name') = 'Juliette'但看来这不是一个有效的表达式。 (I tried this because help(getattr) says getattr(x, 'y') is equivalent to xy ) (我试过这个是因为help(getattr)getattr(x, 'y')相当于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).回答您的具体问题:不,您不能使用getattr替换属性(这是您的示例试图做的)。 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.感谢@Scott Hunter@Richard Neumann在评论部分解决了这个问题。

If you want to set, not get the attribute, use setattr() : setattr(object, attribute, new_value)如果要设置,而不是获取属性,请使用setattr()setattr(object, attribute, new_value)

As mentioned above, you can achieve this by using setattr.如上所述,您可以通过使用 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.但是,这将违反 OOP 中的原则,因为您必须了解有关对象的太多细节,以确保在设置新属性后不会破坏对象的内部行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM