replacing instance __setattr__

Robin Becker robin at jessikat.fsnet.co.uk
Thu Jul 4 07:42:08 EDT 2002


In article <B949E9DF.D666%jonathan at onegoodidea.com>, Jonathan Hogg
<jonathan at onegoodidea.com> writes
>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

special methods aside I find in 'Unifying types and classes in Python
2.2' http://www.python.org/2.2/descrintro.html#mro
that the object is always searched last for methods which seems a bit
daft and obviously different for non-method attributes. 

Maybe that's not true of the 2.2.1 interpreter.

I had always imagined that the object dict was used before anything else
in all cases. We seem to have a lot of special cases for the unwary to
find punji sticks in.



>
>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
>

-- 
Robin Becker



More information about the Python-list mailing list