__future__ and __rdiv__
Massimo Di Pierro
massimo.dipierro at gmail.com
Mon Jan 23 01:17:54 EST 2012
Thank you. I tried __rtruediv__ and it works.
On Jan 23, 2012, at 12:14 AM, Ian Kelly wrote:
> On Sun, Jan 22, 2012 at 10:22 PM, Massimo Di Pierro <massimo.dipierro at gmail.com> wrote:
> Hello everybody,
>
> I hope somebody could help me with this problem. If this is not the right place to ask, please direct me to the right place and apologies.
> I am using Python 2.7 and I am writing some code I want to work on 3.x as well. The problem can be reproduced with this code:
>
> # from __future__ import division
> class Number(object):
> def __init__(self,number):
> self.number=number
> def __rdiv__(self,other):
> return other/self.number
> print 10/Number(5)
>
> It prints 2 as I expect. But if I uncomment the first line, I get:
>
> Traceback (most recent call last):
> File "test.py", line 8, in <module>
> print 10/Number(5)
> TypeError: unsupported operand type(s) for /: 'int' and 'Number'
>
> Is this a bug or the __future__ division in 3.x changed the way operators are overloaded? Where can I read more?
>
>
> In Python 3, the / operator uses __truediv__ and the // operator uses __floordiv__.
> In Python 2, the / operator uses __div__, unless the future import is in effect, and then it uses __truediv__ like Python 3.
>
> http://docs.python.org/reference/datamodel.html#emulating-numeric-types
>
> Cheers,
> Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120123/bb35d6bb/attachment-0001.html>
More information about the Python-list
mailing list