对于此代码,我有"TypeError:/ support支持的操作数类型"
class Foo(object):
def __add__(self, other):
return print("add")
def __div__(self, other):
return print("div")
Foo() + Foo()
add
Run Code Online (Sandbox Code Playgroud)
**但对于/**
Foo() / Foo()
Traceback (most recent call last):
File "<ipython-input-104-8efbe0dde481>", line 1, in <module>
Foo() / Foo()
TypeError: unsupported operand type(s) for /: 'Foo' and 'Foo'
Run Code Online (Sandbox Code Playgroud)
tur*_*too 13
:Python3使用特殊部门的名称__truediv__,并__floordiv__为/和//分别运营.
在Python3中,它/是一个真正的除法,5/2它将返回浮点数2.5.同样5//2是地板师或整数除法,因为它总是会返回一个int,在这种情况下2.
在Python2中,/运算符的工作方式与//运算符在Python3中的工作方式相同.由于操作符在版本之间的更改方式,__div__因此删除了名称以避免歧义.
参考:http://www.diveintopython3.net/special-method-names.html#acts-like-number
| 归档时间: |
|
| 查看次数: |
3697 次 |
| 最近记录: |