下面是一个实现 __iadd__特殊方法的简单自定义类。使用 int 初始化对象,然后可以使用 +=运算符添加数字。我在 __iadd__中添加了一个 print 语句来显示它被调用。而且,__iadd__应该返回一个对象,所以我返回了它本身加上另一个数字,这在本例中是有意义的。
>>> class Adder(object):
def __init__(self, num=0):
self.num = num
def __iadd__(self, other):
print 'in __iadd__', other
self.num = self.num + other
return self.num
>>> a = Adder(2)
>>> a += 3
in __iadd__ 3
>>> a
5
In [1]: x = [2, 3, 4]
In [2]: y = x
In [3]: x += 7, 8, 9
In [4]: x
Out[4]: [2, 3, 4, 7, 8, 9]
In [5]: y
Out[5]: [2, 3, 4, 7, 8, 9]
In [6]: x += [44, 55]
In [7]: x
Out[7]: [2, 3, 4, 7, 8, 9, 44, 55]
In [8]: y
Out[8]: [2, 3, 4, 7, 8, 9, 44, 55]
In [9]: x = x + [33, 22]
In [10]: x
Out[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]
In [11]: y
Out[11]: [2, 3, 4, 7, 8, 9, 44, 55]