Issue with new-style classes and operators
Jan Decaluwe
jan at jandecaluwe.com
Mon Nov 25 07:58:59 EST 2002
Adam Langley wrote:
>
> On Mon, 25 Nov 2002 13:21:37 +0100, Jan Decaluwe wrote:
>
> > class MyInt(object):
> > def __init__(self, val):
> > self.val = val
> > def __getattr__(self, attr):
> > return getattr(self.val, attr)
> >
> >
>
> >>>> a = MyInt(3)
> >>>> a.__add__(4)
> > 7
> >>>> a + 4
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > TypeError: unsupported operand types for +: 'MyInt' and 'int'
>
> (Firstly, I should point out that it *does* work if one makes MyInt an
> old-style class)
>
> Well, the language reference states that:
> "The + (addition) operator yields the sum of its arguments. The
> arguments must either both be numbers or both sequences of the
> same type. In the former case, the numbers are converted to a
> common type and then added together. In the latter case, the
> sequences are concatenated."
>
> Since MyInt is neither a number (not derived from int) nor a sequence, the
> TypeError is technically correct. But, since __add__ is valid, it does
> somewhat violate the principle of least surprise from my point of view.
Note that my example works perfectly fine with old-style classes though,
even though one of the operands is of type 'instance' in that case.
Given python's dynamic nature, I think you should read "is a number"
as "looks like a number".
Regards, Jan
--
Jan Decaluwe
mailto:jan at jandecaluwe.com
More information about the Python-list
mailing list