replacing instance __setattr__

Tim Peters tim.one at comcast.net
Thu Jul 4 13:09:18 EDT 2002


[Robin Becker]
> 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.

The builtin class named "object" is searched last for methods.  When you say
"the object", I expect you're thinking of the x in

    x.somemethod()

That's a different thing entirely.  If x is an instance of a newstyle class,
then x's class either is, or inherits from, the builtin class named
"object", and of course the object class is searched last because object is
at the root of the inheritance hierarchy.  That's waht the MRO discussion is
talking about.  It doesn't even mention x's dict, because x's dict plays no
role in method lookups.

> Maybe that's not true of the 2.2.1 interpreter.

It is.

> I had always imagined that the object dict was used before anything else
> in all cases.

The object dict (x's dict in the above, which has nothing to do with
object's dict) is never searched for methods, and not in any version of
Python.  Methods can only come from classes in Python.  If the name
"somemethod" isn't found in x's class or any of its base classes, then
"somemethod" is not a method of x.  "somemethod" may well be a data
attribute of x that's bound to a function that "acts like" a method, or
close enough to acting like a method that your app doesn't care about the
difference, but even so it's not a method of x if you're careful with words.
An object's (as opposed to the builtin class named object) dict in Python
can only supply data attributes.

> We seem to have a lot of special cases for the unwary to find punji
> sticks in.

Python does draw distictions between instances and classes, and between
method attributes and data attributes.  That was as true in 1.0 as in 2.1.
As they're universally applicable distinctions in Python, "a lot of special
cases" isn't a reasonable characterization.






More information about the Python-list mailing list