是否可以在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__
这样的真实方法?或者,您可以用另一种方式索引自定义类吗?
答案 0 :(得分:5)
您需要实施__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
...