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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With