class Point: # 构造方法,初始化,定义向量坐标 def __init__(self, x, y): self.__x = x self.__y = y # 向量加法,对应分量相加,返回新向量 def __add__(self, other): x = self.__x + other.__x y = self.__y + other.__y return Point(x, y) # 向量减法,对应分量相减,返回新向量 def __sub__(self, other): x = self.__x - other.__x y = self.__y - other.__y return Point(x, y) # 向量乘法,各分量乘以同一个数字,返回新向量 def __mul__(self, a): x = self.__x * a y = self.__y * a return Point(x, y) def __truediv__(self, a): x = self.__x / a y = self.__y / a return Point(x, y) # 若没有这串代码输出的是对象的地址,而不是向量坐标 def show(self): return(self.__x, self.__y) r1 = Point(10, 20) r2 = Point(5, 5) print(r1+r2.show()) print(r1-r2.show()) print((r1*2).show()) print((r1/2).show())错误并改正
时间: 2023-11-11 16:04:55 浏览: 91
11-19-PointClass:创建一个名为 Point 的类,该类将二维空间中某个位置的 (x, y) 坐标存储为整数
错误:在向量加法、向量减法、向量乘法和向量除法的运算中,调用了另一个向量对象的show()方法,导致输出结果不是向量坐标。
改正:在向量加法、向量减法、向量乘法和向量除法的运算中,直接使用另一个向量对象的坐标进行运算即可。
修改后的代码如下:
```python
class Point:
def __init__(self, x, y):
self.__x = x
self.__y = y
def __add__(self, other):
x = self.__x + other.__x
y = self.__y + other.__y
return Point(x, y)
def __sub__(self, other):
x = self.__x - other.__x
y = self.__y - other.__y
return Point(x, y)
def __mul__(self, a):
x = self.__x * a
y = self.__y * a
return Point(x, y)
def __truediv__(self, a):
x = self.__x / a
y = self.__y / a
return Point(x, y)
def show(self):
return (self.__x, self.__y)
r1 = Point(10, 20)
r2 = Point(5, 5)
print((r1+r2).show())
print((r1-r2).show())
print((r1*2).show())
print((r1/2).show())
```
阅读全文