Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why custom types accept ad-hoc attributes in Python (and built-ins don't)?

I'd like to know why one is able to create a new attribute ("new" means "not previously defined in the class body") for an instance of a custom type, but is not able to do the same for a built-in type, like object itself.

A code example:

>>> class SomeClass(object):
...     pass
... 
>>> sc = SomeClass()
>>> sc.name = "AAA"
>>> sc.name
'AAA'
>>> obj = object()
>>> obj.name = "BBB"
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'object' object has no attribute 'name'
like image 890
Chuim Avatar asked Jul 30 '10 18:07

Chuim


1 Answers

Some objects don't have the __dict__ attribute (which is a dictionary that stores all the custom 'newly defined' attributes). You can emulate the same behaviour using the __slots__ variable (see python reference). When you are subclassing a class with __dict__, the __slots__ variable has no effect. And as you are always subclassing object for new style classes, the object mustn't have __dict__, as that would make it impossible to use __slots__. The classes without __slots__ take less memory and are probably slightly faster.

like image 65
ondra Avatar answered Nov 15 '22 18:11

ondra