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