Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I add arbitrary members to object instances? [duplicate]

Tags:

python

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 ?

like image 247
ereOn Avatar asked Oct 21 '22 18:10

ereOn


1 Answers

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
like image 160
Saša Šijak Avatar answered Oct 23 '22 10:10

Saša Šijak