Using setattr() in python - Stack Overflow
python - What's the difference between setattr() and object.__setattr__()? - Stack Overflow
Python's __get/set/delattr__, ordinary assignment versus __setattr__, __dict__ vs dir() - Software Engineering Stack Exchange
python - How does __setattr__ work with class attributes? - Stack Overflow
The Python docs say all that needs to be said, as far as I can see.
setattr(object, name, value)This is the counterpart of
getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,setattr(x, 'foobar', 123)is equivalent tox.foobar = 123.
You are setting self.name to the string "get_thing", not the function get_thing.
If you want self.name to be a function, then you should set it to one:
setattr(self, 'name', self.get_thing)
However, that's completely unnecessary for your other code, because you could just call it directly:
value_returned = self.get_thing()
Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that.
Original Answer*
setattr(instance, name, value) is syntactic sugar for instance.__setattr__(name, value)**.
You would only need to call object.__setattr__(...) inside a class definition, and then only if directly subclassing object -- if you were subclassing something else, Spam for example, then you should either use super() to get the next item in the heirarchy, or call Spam.__setattr__(...) -- this way you don't risk missing behavior that super-classes have defined by skipping over them directly to object.
* applies to Python 3.0+ classes and 2.x new-style classes
**There are two instances where setattr(x, ...) and x.__setattr__(...) are not the same:
xitself has a__setattr__in it's private dictionary (sox.__dict__[__setattr__] = ...(this is almost certainly an error)x.__class__has a__getattribute__method -- because__getattribute__intercepts every lookup, even when the method/attribute exists
NB These two caveats apply to every syntactic sugar shortcut:
setattrgetattrlenboolhash- etc
Here is an example of the difference between setattr and object.__setattr__
class A:
def __init__(self):
self.a = 0
# overriding default behavior
def __setattr__(self, name, value):
self.__dict__[name] = value**2
a = A()
print(a.a) # => 0
a.a = 2
print(a.a) # => 4
setattr(a, 'a', 3)
print(a.a) # => 9
object.__setattr__(a, 'a', 4)
print(a.a) # => 4
To summarize:
setattr()is the function equivalent of the assignment operation. It's like doingmy_obj.name = value.It will call the
__setattr__()method of the object's class, which may be overridden in subclasses.If the attribute is a descriptor,
setattr()will trigger its__set__()method.