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__()
.
For help on it:
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.Usually, we define classes for this.
However, you can, to an extent, do this with the
setattr
andgetattr
built-in functions. However, they don't work on instances ofobject
directly.They do, however, work on all kinds of simple classes.
let x be an object then you can do it two ways