gpt4 book ai didi

Python 对于 __iter__ 的定义实现抛出 TypeError

转载 作者:行者123 更新时间:2023-11-30 23:11:33 24 4
gpt4 key购买 nike

所以我是一名工程师,试图编写一个Python模块,让我可以用科学单位进行计算(我想这已经完成了,但我仍然想自己做)。

我正在对迄今为止编写的代码运行一些测试,并收到以下错误:

File ".../Units/SI_Units.py", line 175, in <module>
N = kg * m / s / s
TypeError: unsupported operand type(s) for /: 'Unit' and 'Unit'

好吧,但我确实为单位定义了 __div__!以下是Unit类中的相关定义:

def __div__(self,other):
if isinstance(other, Unit):
return Unit (self.value / other.value, self.kg - other.kg, self.m - other.m,\
self.s - other.s, self.A - other.A, self.K - other.K,\
self.mol - other.mol, self.cd - other.cd, self.rad - other.rad)
elif isinstance(other, Quantity):
return Quantity (self.value / other.value, self.kg - other.kg, self.m - other.m,\
self.s - other.s, self.A - other.A, self.K - other.K,\
self.mol - other.mol, self.cd - other.cd, self.rad - other.rad)
else:
return Quantity(self.value / other, self.kg, self.m, self.s,self.A,\
self.K, self.mol,self.cd,self.rad)

请注意,即使该行中的单位乘法首先完成,解释器也不会抛出乘法错误。但我实现乘法的方式与实现除法的方式完全相同(显然,除了值相乘并且单位相加)。

怎么了? '/' 确实对应于 __div__,对吗?

最佳答案

使用 __truediv__ 而不是 __div__ 并重试。请参阅Python 3 docs .

__div__ 在 Python 2 中使用。如果导入 __future__.division,Python 2 也会使用 __truediv__。请参阅Python 2 docs 。由于Python 3仅作为新的划分方式,e.i.两个整数相除得到一个 float ,只有 __truediv__存在。

关于Python 对于 __iter__ 的定义实现抛出 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30146494/

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