views:

44

answers:

2

Hi there!

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'
A: 

Good question. I guess it's something along the lines of builtins being implemented in C and that this somehow makes it more complicated to allow "ad hoc attributes", which is not worth it. I'm not proficient with the implementation details, so that's just a guess. But it would certainly make sense.

delnan
+1  A: 

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.

ondra