【发布时间】:2017-10-23 07:56:27
【问题描述】:
我有一个简单的类,编码为:
class test():
def __init__(self, a):
self.a = a
def __add__(self, other):
# returns a test object which is the sum of self and other
return test(self.a + other.a)
def double(self):
print()
print ('meanwhile inside test.double() ...')
operand = test(self.a) # a new test object similar to self
print(' self: ', self)
print(' operand:', operand)
self += operand
print(' -> self: ', self)
def __str__(self):
return '[> %r <]' % self.a
S1 = test(1)
S2 = test(2)
S = S1 + S2
print('sums do work : S = S1 + S2 =', S1, '+', S2, '=', S)
S.double()
print()
print('but S doubled =', S, '??')
输出是:
sums do work : S = S1 + S2 = [> 1 <] + [> 2 <] = [> 3 <]
meanwhile inside test.double() ...
self: [> 3 <]
operand: [> 3 <]
-> self: [> 6 <]
but S doubled = [> 3 <] ??
那么,我怎样才能实现这种行为(即,当从被调用的方法返回时,self 实例将被正确更新)而不必复制所有属性(在实际代码中这些属性很多,并且每次都需要添加属性以重新检查代码以确保复制完成)?
【问题讨论】:
标签: python-3.x class self