Issue with new-style classes and operators

Adam Langley usenet at imperialviolet.org
Mon Nov 25 07:39:01 EST 2002


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.




More information about the Python-list mailing list