首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python自定义类索引

Python自定义类索引
EN

Stack Overflow用户
提问于 2017-01-16 22:27:56
回答 1查看 10.1K关注 0票数 10

是否有可能在python中创建一个类,该类可以用方括号进行索引,但不能从不同的索引类型派生出来?

我对使用可选索引创建一个类感兴趣,它的行为如下所示:

代码语言:javascript
运行
复制
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__这样的真正的方法吗?或者,您可以以其他方式索引自定义类吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-16 22:35:51

您需要实现__getitem__。请注意,单个索引将作为自身传递,而多个索引将作为元组传递。

通常,您可能选择以下列方式处理此问题:

代码语言:javascript
运行
复制
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
        ...
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41686020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档