A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2010-March/098537.html below:

[Python-Dev] binary operation heuristics -- bug or undocumented?

[Python-Dev] binary operation heuristics -- bug or undocumented?Mark Dickinson dickinsm at gmail.com
Fri Mar 19 13:55:58 CET 2010
On Fri, Mar 19, 2010 at 12:46 PM, Alex A. Naanou <alex.nanou at gmail.com> wrote:
> A friend of mine stumbled upon the following behavior:
>
>
> ---cut---
>
>>>> class A(object): pass
> ...
>>>> class B(object):
> ...     def __add__(self, other):
> ...         print 'B: adding B and %s objects.' % other.__class__.__name__
> ...
>>>> class C(object):
> ...     def __radd__(self, other):
> ...         print 'C: adding C and %s objects.' % other.__class__.__name__
> ...
>>>> a, b, c = A(), B(), C()
>
>>>> b + c
> B: adding B and C objects.
>
>>>> a + c
> C: adding C and A objects.
>
>
> # so far, quite logical. now let's do this:
>
>>>> 1 + c
> C: adding C and int objects.
>
>
> --uncut--
>
> My first expectation would be to get a TypeError here, as ints indeed
> have an __add__ method, and they do not know anything about C objects
> (obviously :) ).

Yes:  the int.__add__ method is tried first.  Since it doesn't know
anything about C objects it returns NotImplemented, and then
C.__radd__ is given a chance to do the addition.  The rules are
documented here:

http://docs.python.org/reference/datamodel.html#coercion-rules

Mark
More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4