[Python-Dev] Problems with new-style classes and coercion

Guido van Rossum guido@python.org
Mon, 22 Apr 2002 12:47:06 -0400


> Python 2.2 (#28, Mar 13 2002, 23:18:18) [MSC 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> coerce
> <built-in function coerce>
> >>> class ex(object):
> ...     def __init__(self, v):
> ...             self.v = v
> ...     def __coerce__(self, other):
> ...             return self, ex(other)
> ...     def __add__(self, rhs):
> ...             return ex(self.v + rhs.v)
> ...     def __repr__(self):
> ...             return 'ex(' + repr(self.v) + ')'
> ...
> >>> ex(3)
> ex(3)
> >>> coerce(ex(1),2.3)
> (ex(1), ex(2.2999999999999998))
> >>> ex(1).__add__(ex(2))
> ex(3)
> >>> ex(1)+2.3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 9, in __add__
> AttributeError: 'float' object has no attribute 'v'

New-style classes don't support __coerce__.  It's a long and sad
story, but basically __coerce__ was a mistake, and I've stopped
supporting it for new-style classes.  This means that the + operator
doesn't call __coerce__.  For some reason, coerce() still calls it;
maybe that was a mistake.

--Guido van Rossum (home page: http://www.python.org/~guido/)