Instance of class "object"

Hrvoje Niksic hniksic at xemacs.org
Fri May 16 18:56:20 EDT 2008


"甜瓜" <littlesweetmelon at gmail.com> writes:

>> # an efficient 'Pair' class holding two objects
>> class Pair(object):
>>    __slots__ = 'first', 'second'
>>
>> Instances of Pair take up even less room that 2-element tuples
>> because they don't carry the size information in the object.
>>
>> Now, if the object class carried a dict with it, it would be
>> impossible to create a class like 'Pair'.
>>
> Really interesting. When the tuple ('first', 'second') is assigning
> to __slot__, a special operation is done which makes __slot__
> pointing to a magic structure rather than a normal tuple. Am I
> right?

It's more like this: when the 'Pair' class is created, the class
creation mechanism notices that the class contain a __slots__ member.
It then uses that member as a specification for the layout of
instances of the 'Pair' type.  In this case, instead of a regular dict
(which can hold any number of attributes), Pair instances hold exactly
two attributes, as if[1] it had been declared as:

struct Pair {
  PyObject_HEAD       // type and refcnt, needed for Python
  PyObject *first;    // holds pair.first
  PyObject *second;   // holds pair.second
};

I'm not sure what you mean by "pointing to a magic structure rather
than a normal tuple", but without __slots__, the layout would be
roughly equivalent to:

struct Pair {
  PyObject_HEAD       // type and refcnt, needed for Python
  PyObject *dict;     // holds all pair attributes
};


[1]
I'm intentionally simplifying here, for example omitting weakrefs.



More information about the Python-list mailing list