How do you programmatically set an attribute?

Posted on

Solving problem is about exposing yourself to as many situations as possible like How do you programmatically set an attribute? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How do you programmatically set an attribute?, which can be followed any time. Take easy to follow this discuss.

How do you programmatically set an attribute?

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__().

Asked By: Nick

||

Answer #1:

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.

Answered By: Ali Afshar

Answer #2:

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.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
Answered By: S.Lott

Answer #3:

let x be an object then you can do it two ways

x.attr_name = s
setattr(x, 'attr_name', s)
Answered By: vijay shanker

Answer #4:

Also works fine within a class:

def update_property(self, property, value):
   setattr(self, property, value)
Answered By: d.raev
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published. Required fields are marked *