我正在创建一个代表列表列表的类。 __getitem__ 让我头疼。一切进展顺利,直到我引入切片作为参数。
演示代码
# Python version 2.7.5
class NestedLists:
_Cells = [['.', '.', '.', '.', '.'],
['.', '.', 'N', '.', '.'],
['.', 'C', 'A', 'T', '.'],
['.', '.', 'P', '.', '.'],
['.', '.', '.', '.', '.']]
def __getitem__(self, index):
if isinstance(index, int):
return self._Cells[index]
elif isinstance(index, slice):
return self._Cells[index]
else:
raise TypeError, "Invalid argument type"
nested = NestedLists()
print "Expecting A"
print nested[2][2]
print "Expecting CAT"
print nested[2][1:4]
print "Expecting ..N.."
print " .CAT."
print " ..P.."
print nested[1:4]
print "Expecting .N."
print " CAT"
print " .P."
print nested[1:4][1:4]
输出如下
Expecting A
A
Expecting CAT
['C', 'A', 'T']
Expecting ..N..
.CAT.
..P..
[['.', '.', 'N', '.', '.'], ['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]
Expecting .N.
CAT
.P.
[['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]
显然,发生的情况是第二个 [] 运算符调用被应用于第一个运算符的输出......但保留在最外层列表的上下文中。然而,解决方案却让我无法理解。