What's going on here?

Carl Banks pavlovevidence at gmail.com
Thu Nov 23 21:11:49 EST 2006


Dale Strickland-Clark wrote:
> Thanks for the answers. I am informed but I don't feel enlightened.
>
> It does strike me as odd that an apparently empty subclass should add extra
> function to the base class.
>
> Not at all obvious.

Remember that a class definition is syntax sugar for a direct call to
type:

type(name,bases,clsdict)

This constructs and returns the class.  It's free to add behaviors even
if the clsdict is empty, and that's exactly what it does in this case.
type considers the absence of __slots__ in clsdict to be a request for
an instance dict, and so it adds one.  (Types defined in C aren't
created that way, however.  I believe C-defined types request an
instance dict by reserving space for it in the object structure and
setting tp_dictoffset to indicate its offset.)

This is not obvious, but it's really the only reasonable way.  You
can't have the base class of all objects creating dicts for its
instances--you wouldn't want every int object to have it's own dict.
And you can't have Python class instances not have a dict by default.


Carl Banks




More information about the Python-list mailing list