using an instance of Object as an empty class

Peter Otten __peter__ at web.de
Wed Jun 29 08:00:42 EDT 2011


AlienBaby wrote:

> I'm just wondering why something is so, and whats going on under the
> hood.
> 
> Now and again I use something like
> 
> class empty(object):
>  pass
> 
> 
> simply so I can make an instance, and set some attributes on it.
> 
> a=empty()
> a.whatever=something
> 
> 
> Poking around with this, I assumed I could instead say
> 
> a=object()
> a.whatever=something
> 
> but I get an attribute error. 'object object has no attribute
> whatever'
> 
> I tried setattr() but get the same result.
> 
> 
> So, it seems to me there is something special about instances of
> object, and making an empty class  that inherits from object, or
> creating an instance of that class, is doing some 'magic' somewhere
> that enables setting attributes etc..
> 
> Whats actually going on here, and why?

Normal instances in Python store the contents in a dictionary called 
__dict__. 

a.attribute = 42

is then syntactic sugar for

a.__dict__["attribute"] = 42

As object serves as the base class for classes that don't have a __dict__, 
usually to save memory, it cannot have a __dict__ either. Examples for 
classes that don't accept attributes are builtins like int, tuple, and -- 
obviously -- dict. You can make your own using the __slot__ mechanism:

>>> class A(object):
...     __slots__ = ["x", "y"]
...
>>> a = A()
>>> a.x = 42
>>> a.y = "yadda"
>>> a.z = 123
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'z'






More information about the Python-list mailing list