__eq__ 方法对于 == 和 > 运算符都返回 True

Gau*_*eva 5 python comparison

我在 Python 中声明了一个类Triangle,它以底和高为参数,并有一个计算并返回三角形面积的__init__方法。area该类__eq__的方法Triangle比较三角形的面积并返回值。该类定义如下:

class Shape(object):
    def area(self):
        raise AttributeException("Subclasses should override this method.")

class Triangle(Shape):
    def __init__(self, base, height):
        """
        base = base of the triangle.
        height = height of the triangle
        """
        self.base = base
        self.height = height
    def area(self):
        return (self.base * self.height)/2
    def __str__(self):
        return 'Triangle with base ' + str(self.base) + ' and height ' + str(self.height)
    def __eq__(self, other):
        """
        Two triangles are equal if their area is equal
        """
        return (self.area() == other.area())
Run Code Online (Sandbox Code Playgroud)

现在我运行该程序并创建了两个实例 和Triangle t1t3并给了它们不同的底面和高度,但它们的面积相等。所以t1 == t3应该是True作为True唯一返回的。但奇怪的是,t1 > t3也返回为True,我不明白为什么?

>>> t1 = Triangle(3,4)
>>> t3 = Triangle(2, 6)
>>> t1.area()
6
>>> t3.area()
6
>>> t1 == t3
True
>>> t1 > t3
True
>>> t1 < t3
False
>>> 
Run Code Online (Sandbox Code Playgroud)

L3v*_*han 4

虽然我找不到这方面的资料,但如果id你自己没有定义各自的魔术方法,Python 2 似乎会使用 来比较两个对象。

观察:

>>> t1 = Triangle(3, 4)
>>> t3 = Triangle(2, 6)
>>> t1 > t3
False
>>> t1 < t3
True
>>> t1 = Triangle(3, 4)
>>> t1 > t3
True
>>> t1 < t3
False
Run Code Online (Sandbox Code Playgroud)

这种行为并不能得到保证,因为它不id保证您为以后创建的对象分配越来越多的数字,但它通常似乎在 CPython 2.7 中有效,因为id它将为您提供对象的物理地址。

你会发现,在重新定义t1,之前id(t1) < id(t3),而在重新定义之后,情况恰恰相反。

  • @GauravSachdeva 没有这样的事情可以保证。在 CPython 中,“id”是对象的物理地址。它可以是任何有可用空间的地址(通常,在开头给出递增的数字......) (2认同)