Python 3.1 内联除法重载
我不知道这是不是3.1版本的一个bug,但如果我没记错的话,在3k之前的版本中,“内联”分割是这样工作的:
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def __init__(self, x):
... self.x = x
... def __idiv__(self, y):
... self.x /= y
...
>>> a = A(5)
>>> a /= 2
不过,3.1给我的结果是这样的:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /=: 'A' and 'int'
...还是我漏掉了什么?
1 个回答
6
啊!我发现了 __floordiv__
和 __truediv__
。抱歉!
如果你想告诉我为什么 2to3 不把 __idiv__
转换成 __truediv__
,而是用 __floordiv__(self, y): self.__truediv__(y)
,请随便说!