5

I just realized that:

class A(object): pass

a = A()
a.x = 'whatever'

Works (does not raise an error and creates a new x member).

But this:

a = object()
a.x = 'whatever'

Raises:

AttributeError: 'object' object has no attribute 'x'

While I probably would never use this in real production code, I'm a bit curious about what the reason is for the different behaviors.

Any hints ?

ereOn
  • 48,328
  • 33
  • 147
  • 228
  • Also http://stackoverflow.com/questions/1072649/python-language-question-attributes-of-object-vs-function – interjay Dec 17 '13 at 16:03

1 Answers1

3

Probably because of __slots__. By default your class have dict of all atributes which can be added to like in your first example. But that behaviour can bi overriden by using slots.

Also, some classes like datetime which are implemented in C also can not be extended with new attributes at runtime.

Workaround for such classes is to do something like :

class MyObject():  # extend that class, here we extend object
  pass  # add nothing to the class

o = MyObject()
o.x = 'whatever'  # works
Saša Šijak
  • 7,295
  • 5
  • 41
  • 74