How do you programmatically set an attribute?

后端 未结 4 832
北荒
北荒 2020-11-22 04:41

Suppose I have a python object x and a string s, how do I set the attribute s on x? So:

>>> x =          


        
4条回答
  •  渐次进展
    2020-11-22 05:13

    setattr(x, attr, 'magic')
    

    For help on it:

    >>> help(setattr)
    Help on built-in function setattr in module __builtin__:
    
    setattr(...)
        setattr(object, name, value)
    
        Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
        ``x.y = v''.
    

    Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.

提交回复
热议问题