plain object()

Michael Chermside mcherm at mcherm.com
Thu May 1 14:24:15 EDT 2003


Lee Harr writes:
> Can someone explain this?
    
    [demonstration that "object().x = 3" behaves
     differently than "NewStyleClass().x = 3" where
     NewStyleClass is simply 
     "class NewStyleClass(object): pass"]

The class "object" behaves as if it had "__slots__ = []"
defined. That is, it has no instance __dict__, and you
cannot set arbitrary attributes on it.

A simple subclass of object will NOT behave that way unless
you actually add the line "__slots__ = []". It WILL have
an instance __dict__ and you CAN set arbitrary attributes
on it.

So, for example:

>>> object().x = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute 'x'
>>> class NewObject1(object):
...     pass
...
>>> NewObject1().x = 3
>>> class NewObject2(object):
...     __slots__ = []
...     pass
...
>>> NewObject2().x = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'NewObject2' object has no attribute 'x'







More information about the Python-list mailing list