Python重载多个getitems/索引请求 [英] Python overloading multiple getitems / index requests
本文介绍了Python重载多个getitems/索引请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要使用myGrid[1][2]
访问的Grid
类.我知道我可以使用__getitem__()
方法重载第一组方括号,但是第二组呢?
I have a Grid
class which I want to access using myGrid[1][2]
. I know I can overload the first set of square brackets with the __getitem__()
method, but what about the second.
我想我可以通过创建一个同时实现__getitem__
的帮助程序类来实现此目标,然后:
I thought I could achieve this by having a helper class which also implements __getitem__
and then:
class Grid:
def __init__(self)
self.list = A TWO DIMENSIONAL LIST
...
def __getitem__(self, index):
return GridIndexHelper(self, index)
class GridIndexHelper:
def __init__(self, grid, index1):
self.grid = grid
self.index1 = index1
....
def __getitem__(self, index):
return self.grid.list[self.index1][index]
这似乎有点太自酿了……实现此目标的python方法是什么?
This seems a little too homebrewed... What is the python way to achieve this?
推荐答案
class Grid:
def __init__(self):
self.list = [[1,2], [3,4]]
def __getitem__(self, index):
return self.list[index]
g = Grid();
print g[0]
print g[1]
print g[0][1]
打印
[1, 2]
[3, 4]
2
这篇关于Python重载多个getitems/索引请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文