#it's python 3.2.3
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, point):
self.x += point.x
self.y += point.y
return self
def __repr__(self):
return 'point(%s, %s)' % (self.x, self.y)
class Test:
def __init__(self):
self.test1 = [point(0, i) for i in range(-1, -5, -1)]
self.test2 = [point(i, 0) for i in range(-1, -5, -1)]
print('%s\n+\n%s\n=\n%s' % (self.test1[0], self.test2[0], self.test1[0] + self.test2[0]))
test = Test()
input()
Run Code Online (Sandbox Code Playgroud)
这个程序的输出是
point(-1, -1)
+
point(-1, 0)
=
point(-1, -1)
Run Code Online (Sandbox Code Playgroud)
但它应该是
point(-1, -1)
+
point(-1, 0)
=
point(-2, -1)
Run Code Online (Sandbox Code Playgroud)
但如果我这样做
print(point(-1, -1) + point(-1, 0))
Run Code Online (Sandbox Code Playgroud)
它完美地运作
我想知道为什么,以及如何解决这个问题
抱歉,如果我的英语不好:)
Dou*_*gal 17
您的__add__函数将左侧参数修改为+.例如:
>>> x = point(0, 0)
>>> x + point(1, 1)
point(1, 1)
>>> x
point(1, 1)
Run Code Online (Sandbox Code Playgroud)
你应该改变__add__要像
def __add__(self, oth):
return point(self.x + oth.x, self.y + oth.y)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
241 次 |
| 最近记录: |