这是一个非常简单的类来说明理论:
class Indexable(object):
def __getitem__(self, index):
print("You indexed me with {}.".format(index))
在使用中,则:
>>> i = Indexable()
>>> i[12]
You indexed me with 12.
在这里我们可以清楚地看到,i[12]
解析为Indexable.__getitem__(i, 12)
。
这种情况随处可见 - 即使你打电话self[avariable]
实例方法中(包括__getitem__
),你最终会调用Indexable.__getitem__(self, avariable)
。这解释了无限循环,如果您在Indexable.__getitem__
内包含self[avariable]
。
这将永远是Python的情况下,你不能重新定义这种语法,而无需自己重写。这是一种“神奇的方法”,就像str(instance)
调用Class.__str__(instance)
。
在实践中,你一般会要定义索引一些有益的行为,也许你想假numpy
风格逗号分隔的索引:
class NotArray(object):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
data = self.data
for ind in index:
data = data[ind]
return data
这可以用于像:
>>> arr = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> arr[1, 1, 1]
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
arr[1, 1, 1]
TypeError: list indices must be integers, not tuple
>>> arr = NotArray([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> arr[1, 1, 1]
8
请注意,我们现在已经为给定索引返回的数据定义了一个源。
您也可以使用它来实现非标准的语法,就像我在回答这个问题做:is it possible to add some new syntax in javascript?但这一般不提倡,因为它会混淆你的代码的读者。
数据来自哪里? – ThinkChaos 2014-11-14 17:24:25
@jonrsharpe其实我发布这个问题找到使用像自我[avariable]的确切工作..如果它的posible请张贴它作为答案 – lovemysql 2014-11-14 17:34:18