gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for/:

转载 作者:太空宇宙 更新时间:2023-11-03 12:23:32 33 4
gpt4 key购买 nike

对于此代码,我有“TypeError: unsupported operand type(s) for/:”

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 将返回 float 2.5。类似地,5//2 是一个floor 除法或整数 除法,因为它总是返回一个 int,在本例中是 2.

在 Python2 中,/ 运算符的工作方式与 // 运算符在 Python3 中的工作方式相同。由于操作符在版本之间发生变化的方式,__div__ 名称被删除以避免歧义。

引用:http://www.diveintopython3.net/special-method-names.html#acts-like-number

关于python - 类型错误 : unsupported operand type(s) for/:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40770632/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com