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 ?

1

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.