我认为这取决于是什么v
以及是否可以编辑定义类的代码f
:
对于 wherev
是一个整数的情况,你可以编辑类 `f 的代码,这当然是可能的:
class alist(object):
def __init__(self):
self.L = list()
def append(self, v):
self.L.append(v)
def increase(self, k, i):
self.L[k] += i
def __getitem__(self, k):
return self.L[k]
def __setitem__(self, k, v):
self.L[k] = v
a = alist()
a.append(8)
a.append(1)
a.append(15)
a.append(57)
print "List contains: ", a.L
print "This should be eight: ", a.get(0)
# Increase using the increase method
a.increase(0,2)
print "This should be ten: ", a.get(0)
print "This should be ten: ", a[0]
# Increment using the [] getitem shortcut
a[0] += 2
print "This should be twelve: ", a.get(0)
print "This should be twelve: ", a[0]
print "List contains: ", a.L
其中显示:
List contains: [8, 1, 15, 57]
This should be eight: 8
This should be ten: 10
This should be ten: 10
This should be twelve: 12
This should be twelve: 12
List contains: [12, 1, 15, 57]
无需包装代理类,无需定义,__iadd__
因为它已经为整数定义了。现在,如果您正在使用其他元素数据类型(如自定义对象),您可能需要定义__iadd__
.