简体   繁体   English

Python重载列表索引错误

[英]Python Overloading List Index Error

I am trying to overload the [] operator for a list to work like a circular list. 我正在尝试重载[]运算符,以使列表像循环列表一样工作。

class circularList(list):
    def __init__(self, *args):
        list.__init__(self,args)

    def __getitem__(self, key):
        return list.__getitem__(self, key%self.length)

    def __setitem__(self, key, value):
        return list.__setitem__(self, key%self.length, value)

When running this code in the sage terminal, I get the following error: 在sage终端中运行此代码时,出现以下错误:

TypeError: Error when calling the metaclass bases
    list() takes at most 1 argument (3 given)
sage:     def __getitem__(self, key):
....:             return list.__getitem__(self, key%self.length)
....:     
sage:     def __setitem__(self, key, value):
....:             return list.__setitem__(self, key%self.length, value)

This would be used as follows: 这将被如下使用:

circle = circularlist([1,2,3,4])

Does anyone happen to know what I am doing wrong? 有人碰巧知道我在做什么错吗?

With minor fixes, this works for me using Python 2.7.1: 通过一些小的修复,这对于使用Python 2.7.1的用户来说是有效的:

class circularList(list):
    def __init__(self, *args):
        list.__init__(self,args)

    def __getitem__(self, key):
        return list.__getitem__(self, key%len(self))        # Fixed self.length

    def __setitem__(self, key, value):
        return list.__setitem__(self, key%len(self), value) # Fixed self.length

circle = circularList(1,2,3,4)                              # Fixed uppercase 'L'
                                                            # pass values are argument 
                                                            # (not wrapped in a list)
print circle
for i in range(0,10):
    print i,circle[i]

Producing: 生产:

[1, 2, 3, 4]
0 1
1 2
2 3
3 4
4 1
5 2
6 3
7 4
8 1
9 2

BTW, are you aware of itertools.cycle ? 顺便说一句,您知道itertools.cycle吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM