是否有可能在python中创建一个类,该类可以用方括号进行索引,但不能从不同的索引类型派生出来?
我对使用可选索引创建一个类感兴趣,它的行为如下所示:
class indexed_array():
def __init__(self, values):
self.values = values
def __sqb__(self, indices): #This is a made up thing that would convert square brackets to a function
if len(indices) == 2:
return self.values[indices[0]][indices[1]]
elif len(indices) == 1:
return self.values[indices[0]][0]
myarray = indexed_array([[1,2,3], [4,5,6], [7,8,9]])
print myarray[1, 1] # returns 5
print myarray[1] # returns 4
有像我的__sqb__
这样的真正的方法吗?或者,您可以以其他方式索引自定义类吗?
发布于 2017-01-16 22:35:51
您需要实现__getitem__
。请注意,单个索引将作为自身传递,而多个索引将作为元组传递。
通常,您可能选择以下列方式处理此问题:
class indexed_array:
def __getitem__(self, indices):
# convert a simple index x[y] to a tuple for consistency
if not isinstance(indices, tuple):
indices = tuple(indices)
# now handle the different dimensional cases
...
https://stackoverflow.com/questions/41686020
复制相似问题