views:

2705

answers:

2

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

>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'

What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().

+10  A: 
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 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.

Ali A
Careful, however, this doesn't work in your scenario where you're creating an instance of object().
S.Lott
Absolutely right, it doesn't. I conveniently ignored that. I would strongly urge the O.P. to never make instances of object like that.
Ali A
+1: "never make instances of object like that"
S.Lott
+6  A: 

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       x.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.MyAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr
S.Lott