Overloading operators on the rigth.

Alex Martelli aleaxit at yahoo.com
Wed Oct 13 10:18:28 CEST 2004


Bengt Richter <bokr at oz.net> wrote:
   ...
> >>>> class foo:
> >...   def __getattr__(self, name):
   ...
> On my system, (NT4, python 2.3.2) what really happens for newstyle classes
> isn't apparent from that experiment:

Heh, of course not -- the main difference between old-style and
new-style classes is that, for the latter, implicit lookup of special
methods when needed for operations starts with the *class*, not with the
*instance*.  This is a fix of a long-standing design bug, because the
old rule was just impossible to apply consistently -- if calling X meant
looking for X.__call__ rather than X.__class__.__call__, how could you
ever instantiate X by calling it, when X is a class whose _instances_
are meant to be callable, for example?

Since this has been discussed many times on this group, as well as in
presentations, articles, websites, books, ..., I didn't think it was
necessary to dwell on the issue again, considering it really did not
affect the answer requested by the original poster; apparently I was
wrong in so thinking.  _Sigh_ -- next time somebody criticizes my posts
as being too long, I'll retort that of course they are, if I must keep
repeating such issues!-)

I just used an old-style class because, that way, I could show the
lookups happening without having to code a custom metaclass.  The
special names being looked for are just the same, whether for classic or
newstyle classes, anyway -- all that changes is _where_ they're looked
up (starting on the instance, vs starting on the class).

 
>  >>> class foo(object):
>  ...   def __getattr__(self, name):
>  ...     print 'looking for %r' % name
>  ...     raise AttributeError, name
>  ...
>  >>> f=foo()
>  >>> 12 < f
>  True
> 
> The old style does work much the same (but note the default end result ;-)
> Is that a 2.3.2 bug?

No bug: comparisons between objects of disparate types give essentially
arbitrary results (repeatable within one run, but, at least in theory,
potentially different among runs of the same program, I believe).


Alex



More information about the Python-list mailing list