python – TypeError:/不支持的操作数类型:
发布时间:2020-12-20 12:33:45 所属栏目:Python 来源:网络整理
导读:对于此代码,我有“TypeError:/ support支持的操作数类型” class Foo(object): def __add__(self,other): return print("add") def __div__(self,other): return print("div")Foo() + Foo()add ** 但对于 / ** Foo() / Foo()Traceback (most recent call la
对于此代码,我有“TypeError:/ support支持的操作数类型”
class Foo(object): def __add__(self,other): return print("add") def __div__(self,other): return print("div") Foo() + Foo() add ** 但对于 / ** 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' 解决方法
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |