[Tutor] object's attributes

Kent Johnson kent37 at tds.net
Fri Jan 2 17:57:32 CET 2009


On Fri, Jan 2, 2009 at 11:10 AM, spir <denis.spir at free.fr> wrote:
> Can someone explain the following?
>
> ============================
> class Type(object):
>        pass
> o = Type()
> o.a = 1
> print o, o.a
> print dir(object)
> ==> ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__',
> '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']
> ==> no problem
> o = object()
> o.a = 1
> ==> AttributeError: 'object' object has no attribute 'a'
> ================================
>
> Type does not create any additional attribute or member, or what?
> Does this mean that the type 'object' has a hidden __slots__ attr?
> Then why doesn't Type inherit it, like any attribute?

I'm no expert on this so take this with salt...

IIUC the attributes of built-in objects are hard-coded in tables. The
hard-coded tables don't include __dict__ attributes so you can't add
attributes to instances of built-in types. This is similar to what
__slots__ does for user-defined classes though the implementation is
different.

The special behaviour of a class with a __slots__ attribute only
affects the class that defines __slots__, not subclasses. See
http://docs.python.org/reference/datamodel.html#id3: "The action of a
__slots__ declaration is limited to the class where it is defined. As
a result, subclasses will have a __dict__ unless they also define
__slots__."

Kent


More information about the Tutor mailing list