5.27

import math

===================== 平面点类 Point =====================

class Point:
# 构造函数:初始化x, y坐标
def init(self, x=0, y=0):
self.x = x # 横坐标
self.y = y # 纵坐标

-------------------- 计算到原点(0,0)的距离 --------------------

def distance(self):
# 距离公式:√(x² + y²)
return math.sqrt(self.x ** 2 + self.y ** 2)

-------------------- 重载 < 运算符 --------------------

def lt(self, other):
# 比较:当前点距离 < 另一个点距离
return self.distance() < other.distance()

-------------------- 重载 <= 运算符 --------------------

def le(self, other):
return self.distance() <= other.distance()

-------------------- 重载 > 运算符 --------------------

def gt(self, other):
return self.distance() > other.distance()

-------------------- 重载 >= 运算符 --------------------

def ge(self, other):
return self.distance() >= other.distance()

-------------------- 重载 == 运算符 --------------------

def eq(self, other):
return self.distance() == other.distance()

-------------------- 重载 != 运算符 --------------------

def ne(self, other):
return self.distance() != other.distance()

-------------------- 显示点信息和距离 --------------------

def show(self):
print(f"点({self.x}, {self.y}),到原点距离:{self.distance():.2f}")

===================== 测试程序 =====================

if name == 'main':
# 创建三个点对象
p1 = Point(1, 1) # 距离≈1.41
p2 = Point(3, 4) # 距离=5.00
p3 = Point(3, 4) # 距离=5.00

print("===== 各点信息 =====")
p1.show()
p2.show()
p3.show()

print("\n===== 关系运算测试 =====")
print(f"p1 < p2 :{p1 < p2}") # True
print(f"p1 > p2 :{p1 > p2}") # False
print(f"p2 == p3:{p2 == p3}") # True
print(f"p1 == p2:{p1 == p2}") # False
print(f"p2 >= p3:{p2 >= p3}") # True
print(f"p1 <= p3:{p1 <= p3}") # True

posted @ 2026-06-19 20:49  Cx330。  阅读(2)  评论(0)    收藏  举报