2014-11-14 78 views
0

我想知道我是否可以使用像self[avariable]这样的方括号,所以我实现了__getitem__。我曾尝试代码:使用方括号“自我”

class myclass: 
    def __getitem__(self,index): 
     return self[index] 

babe = myclass() 
print babe[4] 

当我运行这个它表明:

File "C:/Python27/df", line 3, in __getitem__ 
    return self[index] 

递归。

如何在Python中使用像self[name]__getitem__这样的变量?

+0

数据来自哪里? – ThinkChaos 2014-11-14 17:24:25

+0

@jonrsharpe其实我发布这个问题找到使用像自我[avariable]的确切工作..如果它的posible请张贴它作为答案 – lovemysql 2014-11-14 17:34:18

回答

4

你的班级需要有东西来索引,而不是self。例如,在这个类foo中,它有一个成员变量data,它是一个列表。因此,例如,索引操作可以索引列表data

class foo(): 
    def __init__(self, l): 
     self.data = l 

    def __getitem__(self, index): 
     return self.data[index] 

>>> a = foo([1,2,3]) 
>>> a[1] 
2 
+0

@Cybr ..有什么办法,我可以使用像自我[avariable] ? – lovemysql 2014-11-14 17:26:01

+2

'self [avariable]'会调用'self .__ getitem __(avariable)',因此你陷入循环。在'__getitem__'里面,你需要确定数据应该来自哪里(在本例中为'self.data')。 – jonrsharpe 2014-11-14 17:26:59

+0

@jonrsharpe你可以给我一个像自我使用的代码。[avariable] ?? ..这是可能的python ,,然后请发布一个例子作为答案 – lovemysql 2014-11-14 17:32:39

0
class myclass(list): 
    def __getitem__(self, key): 
     return super(myclass, self).__getitem__(key-1) 

babe = myclass() 
babe.append(1) 
babe.append(2) 
babe.append(3) 
babe.append(4) 
print babe[4] 
1

这是一个非常简单的类来说明理论:

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?但这一般不提倡,因为它会混淆你的代码的读者。