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

1

10

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'
Yeeyegg answered 30/7, 2010 at 18:52 Comment(0)
V
6

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.

Vday answered 30/7, 2010 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.