The __eq__ method returns True for the == and> operators

I declared a class Trianglein Python that takes base and height as __init__arguments and has a method areathat calculates and returns the area of ​​the triangle. The __eq__class method Trianglecompares the area of ​​the triangles and returns a value. The class is defined as follows:

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())

Now I started the program and created two instances for Triangle t1and t3, and gave them different bases and heights, but their area is equal. Therefore, there t1 == t3must be Trueone that returns only as True. But oddly enough, it t1 > t3also returns like Truethat, which I don’t understand why?

>>> t1 = Triangle(3,4)
>>> t3 = Triangle(2, 6)
>>> t1.area()
6
>>> t3.area()
6
>>> t1 == t3
True
>>> t1 > t3
True
>>> t1 < t3
False
>>> 
+4
2

, , Python 2 id , .

:

>>> t1 = Triangle(3, 4)
>>> t3 = Triangle(2, 6)
>>> t1 > t3
False
>>> t1 < t3
True
>>> t1 = Triangle(3, 4)
>>> t1 > t3
True
>>> t1 < t3
False

, id , , CPython 2.7, id .

, t1, id(t1) < id(t3), , , .

+3

docs

__cmp __(), __eq __() __ne __(), ( "" ).

, python 2 .

__gt__ __lt__ __eq__ , . , __le__, __ge__, __ne__...

, :

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())
    def __gt__(self, other):
        """
        This works for both greater than and less than
        """
        return (self.area() > other.area())
+2

Source: https://habr.com/ru/post/1672061/


All Articles