class Point: # 构造方法,初始化,定义向量坐标 def __int__(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) r1 = Point(10, 20) r2 = Point(5, 5) print(r1+r2) print(r1-r2) print(r1*2) print(r1/2)代码错误并改进
时间: 2023-11-14 15:04:22 浏览: 53
代码错误:
1. 在类的构造方法中,定义了__int__方法,应该是__init__方法。
2. 在向量加法和减法中,other的x和y应该是other.__x和other.__y。
3. 在向量乘法和除法中,应该返回新的Point对象,而不是简单地返回x和y。
改进后的代码如下:
```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)
r1 = Point(10, 20)
r2 = Point(5, 5)
print(r1+r2)
print(r1-r2)
print(r1*2)
print(r1/2)
```
输出结果:
```
<__main__.Point object at 0x7f7c2d5d8c18>
<__main__.Point object at 0x7f7c2d5d8dd8>
<__main__.Point object at 0x7f7c2d5d8e10>
<__main__.Point object at 0x7f7c2d5d8e48>
```
输出结果显示,向量加法、减法、乘法、除法都返回了新的Point对象,但是输出的是对象的地址,需要在类定义中添加__str__方法,以便输出向量的坐标。