【问题标题】:Python Overloading List Index ErrorPython重载列表索引错误
【发布时间】:2014-08-20 17:41:44
【问题描述】:

我正在尝试重载 [] 运算符以使列表像循环列表一样工作。

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)

在 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)

这将按如下方式使用:

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

有没有人碰巧知道我做错了什么?

【问题讨论】:

  • 如何调用你的构造函数(即circularList(...))?
  • 定义类时出现此错误,我将更新帖子。
  • 你甚至根本不需要__init__,首先。超类 __init__ 可以很好地解决问题,因为您不再添加任何属性。
  • 他确实需要__init__,因为他将参数列表转换为列表项(这意味着您可以将任意数量的项传递给构造函数,而不必将可迭代的类似传递给list )
  • 您使用circularList 的方式最终会创建一个类似于[[1, 2, 3, 4]] 的列表,因为您在构造函数中使用了参数列表。要么不需要*(在这种情况下,您可以删除构造函数,请参阅@TheSoundDefense 的评论),或者您真的想将其称为circularList(1, 2, 3, 4) 以创建类似[1, 2, 3, 4] 的列表

标签: python constructor overloading sage


【解决方案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]

制作:

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

顺便说一句,你知道itertools.cycle 吗?

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2013-04-07
    • 2014-08-11
    • 2016-07-31
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2015-01-28
    • 2018-02-07
    相关资源
    最近更新 更多