[Python-Dev] summing integer and class
Greg Ewing
greg.ewing at canterbury.ac.nz
Fri Oct 4 00:58:56 CEST 2013
Igor Vasilyev wrote:
> class A():
> def __add__(self, var):
> print("I'm in A class")
> return 5
> a = A()
> a+1
> 1+a
>
> Execution:
> python test.py
> I'm in A class
> Traceback (most recent call last):
> File "../../test.py", line 7, in <module>
> 1+a
> TypeError: unsupported operand type(s) for +: 'int' and 'instance'
You need to define an __radd__ method for it to work
as a right-hand operand.
> When we adding class to integer we have both slotv and slotw. x =
> slotv(v, w); -> returns Py_NotImplemented.
> But in this case we should execute x = slotw(v, w);
Yes, but the wrapper that gets put in the type slot calls
__rxxx__ instead of __xxx__ if it's being called for the
right-hand operand.
--
Greg
More information about the Python-Dev
mailing list