Python重载列表索引错误
我试图重载[]操作符,使列表像循环列表一样工作Python重载列表索引错误,python,constructor,overloading,sage,Python,Constructor,Overloading,Sage,我试图重载[]操作符,使列表像循环列表一样工作 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):
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])
有人知道我做错了什么吗?通过一些小的修正,我可以使用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
顺便说一句,你知道吗?你如何调用你的构造函数(即,
循环列表(…)
)?当我定义类时会发生此错误,我将更新帖子。首先,你甚至不需要\uuu init\uuuu
。超类\uuuuu init\uuuuu
可以很好地完成这一任务,因为您不需要再添加任何属性。他确实需要\uuuuuu init\uuuuu
,因为他将参数列表转换为列表项(这意味着您可以将任意数量的项传递给构造函数,而不必像list
那样传递iterable)使用circularList
的方法,最终会创建一个类似于[[1,2,3,4]]
的列表,因为您在构造函数上使用了参数列表。要么不需要*
(在这种情况下,您可以删除构造函数,请参阅@TheSoundDefense的注释),要么您真的想将其称为循环列表(1,2,3,4)
,以创建类似[1,2,3,4]