Bug overriding operators in new-style classes?

Steven Taschuk staschuk at telusplanet.net
Thu Jul 17 20:31:33 EDT 2003


Quoth Nicodemus:
> I found a surprising behavior regarding new-style classes operator lookup.
> It seems that for operators, the instance methods are ignored. Observe:
  [...]
> Is this a bug, or am I missing something? Any help would be appreciated.

Working as designed, I think [1], though I've never actually seen
it documented.  As you have observed, invocation of a magic method
(such as __add__ or __len__) by way of a special notation (such as
+ or len()) ignores the instance dict.  That is,
    len(x)
is not equivalent to
    x.__len__()
(which would find __len__ in the instance dict by normal attribute
access) but to
    type(x).__len__(x)
(which obviously ignores the instance dict).

We get this question fairly frequently.  (Last time I think it was
about the iterator protocol's .next() method.)  It really ought to
be documented somewhere; the obvious place would be
    <http://www.python.org/2.2.2/descrintro.html>
(until the real documentation catches up).  Anybody want to write
a patch?

[1] One reason I think it's intended is that these protocols
specify a self argument; for new-style classes, this is provided
by the descriptor machinery, which by design works only when the
function is found in the class dict.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list