考虑下面的代码:
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__
内部运行的任何其他代码都不会被调用
您的
__getitem__
只是返回第一级子列表,因此您可以继续使用下标访问第二级子列表,依此类推,因为返回列表有自己的__getitem__
实现另一方面,您的
__setitem__
需要一个3项元组,因此这应该是您想要的__setitem__
:另一方面,如果您希望能够做到:
您甚至不需要实现
__setitem__
,因为myMDL2[0]
返回第一个子列表,myMDL2[0][0]
返回myMDL2[0]
的第一个子列表,然后myMDL2[0][0][0] = 12
将调用myMDL2[0][0]
返回的列表的__setitem__
方法因为
相当于
但是,
相当于
这意味着首先
myMDL2[0]
完成,我们得到它的第一项,最后我们用值12设置它的第一项我不确定我是否解释得很好,
__setitem__
不是对multiDimList2的调用相关问题 更多 >
编程相关推荐