Why the following code produces an error
>>> object().foo = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
while the next one works fine?
class A():
pass
A().foo = 'bar'
What is the exact difference between A and object? I believe o().foo = 'bar'
leads to setattr('o', 'foo', 'bar')
and this in turn results in o.__setattr__('foo', 'bar')
. One would expect them to have identic __setattr__
methods since no overriding happens. Yet the outputs are different. Please explain why. What happens behind the scenes?
A similar pattern can be noticed for built-in functions and user-defined ones. I can't set my own attributes for let's say dict
but it's perfectly ok to write (lambda:None).foo = 'bar'
. What's going on here?