0

I have this code:

class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    
    def __add__(self, other):
        return Point((self.x ** 2) + (other.x ** 2), (self.y ** 2) + (other.y ** 2), (self.z ** 2) + (other.z ** 2))

    def __str__(self):
        return f'x: {self.x}, y: {self.y}, z: {self.z}'

pt1 = Point(3, 4, -5)
pt2 = Point(-4, 1, 3)

pt3 = pt1 + pt2

print(pt1 == pt2)

Now I want to change == in the last line to > or <, but this error was raised:

TypeError: '>' not supported between instances of 'Point' and 'Point'

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Al3tiby0
  • 9
  • 1

1 Answers1

2

These are the so-called "rich comparison" methods.

object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

The correspondence between operator symbols and method names is as follows:

  • x<y calls x.__lt__(y)
  • x<=y calls x.__le__(y)
  • x==y calls x.__eq__(y)
  • x!=y calls x.__ne__(y)
  • x>y calls x.__gt__(y)
  • x>=y calls x.__ge__(y).

Reference

Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
FavorMylikes
  • 1,182
  • 11
  • 20