考虑以下代码:
class multiDimList1(object):
def __init__(self):
self.data = [[[0, 1, 2], [3, 4, 5], [6, 7, 8]],
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]]
def __getitem__(self, index):
print("MDL1 getitem")
return self.data[index]
def __setitem__(self, index, value):
print("MDL1 setitem")
index, row, col = index
self.data[index][row][col] = value
def __str__(self):
return ','.join(str(e) for e in self.data)
class multiDimList2(object):
def __init__(self):
self.data = [[[0, 1, 2], [3, 4, 5], [6, 7, 8]],
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]]
def __getitem__(self, index):
print("MDL2 getitem")
return self.data[index]
def __setitem__(self, index, value):
print("MDL2 getitem")
index, row, col = index
self.data[index][row][col] = value
def __str__(self):
return ','.join(str(e) for e in self.data)
myMDL1 = multiDimList1()
myMDL2 = multiDimList2()
myMDL1[0, 0, 0] = 12
print(myMDL1)
myMDL2[0][0][0] = 12
print(myMDL2)
输出:
MDL1 setitem
[[12, 1, 2], [3, 4, 5], [6, 7, 8]],[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
MDL2 getitem
[[12, 1, 2], [3, 4, 5], [6, 7, 8]],[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
为什么我可以调用myMDL2[0][0][0]
并__getitem__
适当地处理它,但是尝试分配给该索引却没有调用__setitem__
。
myMDL2[0][0][0] = 12
通过__getitem__
并以这种方式设置对正确索引的引用。这意味着__setitem__
永远不会调用我想在其中运行的任何其他代码。
这是因为
myMDL1[0, 0, 0] = 12
相当于
myMDL1.__setitem__(index=(0,0,0), value=12)
然而,
myMDL2[0][0][0] = 12
相当于
myMDL2.__getitem__(index=0)[0][0] = 12
这意味着首先myMDL2[0]
完成,我们得到它的第一项,最后我们将它的第一项设置为值12。
myMDL2[0][0][0] = 12
=> myMDL2.__getitem__(index=0)[0][0] = 12
=> [[0, 1, 2], [3, 4, 5], [6, 7, 8]][0][0] = 12
=> [[0, 1, 2], [3, 4, 5], [6, 7, 8]].__getitem__(index=0)[0] = 12
=> [0, 1, 2][0] = 12
=> [0, 1, 2].__setitem__(index=0, value=12)
=> [12, 1, 2]
不确定我是否很好地解释__setitem__
了您的multiDimList2上的不是调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句