1

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?

Ponewor
  • 101
  • 2
  • 5
  • Take a look at: https://stackoverflow.com/a/44880260/3444923, object's instance does not have `__dict__`. The simplest check is just dir(...) what you want to check. dir(lamda: None) show that lambda type has `__dict__` – hunzter May 02 '19 at 05:11

0 Answers0