Reputation: 6079
I want to change some attributes of a class programmtically.
I found, that there's the setattr
-function, but it does not work as exptected.
> obj.setattr('bar', 99)
'MyClass' object has no attribute 'setattr'
Instead, I have to use
> setattr(obj, 'bar', 99)
Why is this? I thought, in python the call of a method by an object sets the object itself as the first parameter and so both should mean the same.
Or does Object
simply not has the definition of setattr
?
Upvotes: 1
Views: 2850
Reputation: 7255
The object
setattr method is __setattr__
:
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
And __setattr__('y', v)
will be called when you use x.y = v
.
The help info of setattr
:
setattr(x, 'y', v) is equivalent to ``x.y = v''.
So setattr(x, 'y', v)
is equivalent to x.y = v
and then equivalent to x.__setattr__('y', v)
Upvotes: 3