1

I was trying out dynamic attribute assignment for testing purposes and discovered following behavior:

>>> class Foo(object): pass
... 
>>> bar = Spam()
>>> bar.a = 1
>>> spam = object()
>>> spam.a = 2
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'object' object has no attribute 'a'

Why is the first version with a derived class legit, but the second direct usage of object not? It seems a bit strange to me because deriving hasn't changed anything that has obviously something to do with how variable assignment is handled.

f4lco
  • 3,588
  • 3
  • 25
  • 51

2 Answers2

2

That's because object is a native type, meaning that it's implemented in C code and does not support dynamic attribute assignment, for performance reasons. The same can be said for most Python native classes, such as str or int.

But Python allows you to subclass any native type and your subclasses do support dynamic assignment.

You can disable it for performance reasons on your classes too, using the __slots__ special attribute.

Tobia
  • 14,998
  • 3
  • 64
  • 78
1

object instances don't have a __dict__.

>>> hasattr(object(), '__dict__')
False

And therefore can't have any attributes added to them.

Dan D.
  • 67,516
  • 13
  • 93
  • 109