定义一个平面点类Point,对其重载运算符关系运算符,关系运算以距离坐标原点的远近作为基准,远的为大。程序完成对其的测试。
import math class Point(): def __init__(self, x, y): self.x = x self.y = y def __lt__(self, other): l1 = math.sqrt(self.x ** 2 + self.y ** 2) l2 = math.sqrt(other.x ** 2 + other.y ** 2) return l1 > l2 def __le__(self, other): l1 = math.sqrt(self.x ** 2 + self.y ** 2) l2 = math.sqrt(other.x ** 2 + other.y ** 2) return l1 == l2 def __gt__(self, other): l1 = math.sqrt(self.x ** 2 + self.y ** 2) l2 = math.sqrt(other.x ** 2 + other.y ** 2) return l1 < l2 def __ge__(self, other): l1 = math.sqrt(self.x ** 2 + self.y ** 2) l2 = math.sqrt(other.x ** 2 + other.y ** 2) return l1 >= l2 def __eq__(self, other): l1 = math.sqrt(self.x ** 2 + self.y ** 2) l2 = math.sqrt(other.x ** 2 + other.y ** 2) return l1 <= l2 def __ne__(self, other): l1 = math.sqrt(self.x ** 2 + self.y ** 2) l2 = math.sqrt(other.x ** 2 + other.y ** 2) return l1 != l2 p1 = Point(5, 4) p2 = Point(6, 7) p = p1 > p2 print(p) p = p1 == p2 print(p) p = p1 < p2 print(p) p = p1 >= p2 print(p) p = p1 <= p2 print(p) p = p1 != p2 print(p)