replacing instance __setattr__

Jonathan Hogg jonathan at onegoodidea.com
Thu Jul 4 07:02:39 EDT 2002


On 4/7/2002 10:24, in article D1NxKLAkRBJ9Ew3i at jessikat.demon.co.uk, "Robin
Becker" <robin at jessikat.fsnet.co.uk> wrote:

> well it seems Python not as dynamic as I believed. The object is
> searched last which seems completely counter-intuitive to me, but there
> you go.

It makes sense when you think about it. The special __*attr__ methods are
the mechanism by which one searches the instance and class dictionaries. You
can't get to the instance dictionary without going through one of these
methods first.

When you do:

>>> foo.bar

it roughly translates in the interpreter to:

>>> type(foo).__getattr__('bar')

The default __getattr__ method (the one in 'object') looks something like
(again, using Python pseudo-code - it's actually all C):

    def __getattr__( self, name ):
        if name in self.__slots__:
            index = self.__slots__.index( name )
            return contents_of_slot( self, index )
        elif has_dict(self) and name in self.__dict__:
            return self.__dict__[name]
        elif name in self.__class__.__dict__:
            return self.__class__.__dict__[name]
        else:
            raise AttributeError( "... no attribute '%s'" % name )

The __*attr__ methods aren't actually found through the class dictionary,
they are stored in special slots in the type object and hit directly.

The type of an object is about the only thing you can reliably query. Every
object is guaranteed to have a type. So the interpreter always asks the type
any complicated questions about an object, such as: please retrieve the
following attribute.

[Anyone feel free to jump in and correct my rather loose explanation of the
internals.]

Jonathan




More information about the Python-list mailing list