【发布时间】:2021-08-05 12:21:53
【问题描述】:
def main() :
a = Complex(3.0,-4.5)
b = Complex(4.0, -5.0)
c = Complex(-1.0, 0.5)
print(a+b)
print(a+b-c)
print(a-b)
print(a-b+c)
print(a-c)
print(b == (a-c))
class Complex:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Complex(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Complex(self.x - other.x, self.y - other.y)
def __str__(self):
return f"Complex({self.x}, {self.y})"
main()
我想得到这样的答案:
Complex(7.0,-9.5)
Complex(8.0,-10.0)
Complex(-1.0,0.5)
Complex(-2.0,1.0)
Complex(4.0,-5.0)
True
在Complex(4.0, -5.0) 之前一切正常,但最后我得到了“False”。所以我尝试调试并发现<__main__.Complex object at 0x0397~~~> == <__main__.Complex object at 0x03E7~~~>('at'之后的数字不同)所以显示False。我尝试了print(a-c) 和print(b),它们在打印时看起来相同,但地址之类的东西不同。我应该怎么做才能得到True 而不是False?
【问题讨论】:
-
你的类没有实现
__eq__,或者任何比较方法。 -
您需要定义一个
__eq__方法(可能还有其他比较方法)来覆盖默认的对象相等检查。 -
object at 0x0397只是内存地址,所以2个对象有不同的地址,这是正常的。还可以阅读 stackoverflow.com/questions/1436703/… 以获得您的对象的可读性很好的打印 -
你知道 Python 内置了复数,对吧?例如
a = 3+-4.5j
标签: python