【问题标题】:Calculating Problem when using class in python [duplicate]在python中使用类时计算问题[重复]
【发布时间】: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


【解决方案1】:

正如 cmets 中所指出的,您尚未定义用于相等比较 (==) 的 __eq__ 运算符。由于没有定义,python 不知道如何比较这两者,而是尝试比较它们的身份,如 is 关键字,它检查它们是否是相同的对象(at 之后的地址或“数字”是相同的) .

这是__eq__的一种实现

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})"

    #returns True if the two objects are equal
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

main()

你应该得到True作为你的最终输出

【讨论】:

  • 永远不应该比较浮点数是否相等。请改用 epsilon 球标准。 floating-point-gui.de/errors/comparison
  • 非常感谢!它有效,但我收到了一些小警告 Implementing _eq_ without also implementation _hash_ 这是否意味着当我使用 eq 时,我总是必须使用 hash?
【解决方案2】:

一个快速(但较弱)的解决方案是改变线路

print(b == (a-c))

进入

print(str(b) == str(a-c))

但是,如果您想实现更简单的相等检查,您应该查看 dunder 方法 __eq__。例如,您可以添加方法:

def __eq__(self, other):
    return (self.x, self.y) == (other.x, other.y)

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2014-07-16
    • 2021-07-07
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多