用python语言设计一个二维坐标轴中的位置点类Point,并实现对该类对象之间的加法、减法以及该对象与一个整数的乘法和除法运算。
时间: 2023-12-10 20:38:37 浏览: 125
下面是Point类的实现:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
if isinstance(other, int):
return Point(self.x * other, self.y * other)
else:
raise TypeError("unsupported operand type(s) for *: '{}' and '{}'".format(type(self).__name__, type(other).__name__))
def __truediv__(self, other):
if isinstance(other, int):
return Point(self.x / other, self.y / other)
else:
raise TypeError("unsupported operand type(s) for /: '{}' and '{}'".format(type(self).__name__, type(other).__name__))
```
使用方法如下:
```python
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
p4 = p2 - p1
p5 = p1 * 3
p6 = p2 / 2
print("p1 + p2 =", p3.x, p3.y)
print("p2 - p1 =", p4.x, p4.y)
print("p1 * 3 =", p5.x, p5.y)
print("p2 / 2 =", p6.x, p6.y)
```
输出结果:
```
p1 + p2 = 4 6
p2 - p1 = 2 2
p1 * 3 = 3 6
p2 / 2 = 1.5 2.0
```
阅读全文