gpt4 book ai didi

python - 超出最大递归深度,覆盖 UserList 下新类中的方法

转载 作者:行者123 更新时间:2023-11-30 23:33:27 26 4
gpt4 key购买 nike

我正在 UserList 中创建一个新类,并尝试重写 add、append 和extend 方法,以便任何这些操作都不会将重复值添加到列表中。到目前为止,我已经开始尝试重写追加方法,当我尝试在对象上实现该类时,我收到错误:超出最大递归深度。这是我到目前为止所拥有的:

from collections import UserList

class UList(UserList):
def append(self,item):
for s in self:
if item == s:
print ("Item already exists in list")
else:
self.append(item)


x = [1,2,3,4,5]
z = UList(x)
print (z)
z.append(1)

最佳答案

您递归地调用相同的方法,请调用基类的 append 方法以防止无限递归:

Py2.x:

super(UList, self).append(item)

Py3.x:

super().append(item)

使用 in 运算符而不是循环遍历整个列表来检查项目是否存在。

代码:

from collections import UserList

class UList(UserList):
def append(self, item):
if item in self:
print ("Item already exists in list")
else:
super(UList, self).append(item) # just `super().append(item)` in py3.x

关于python - 超出最大递归深度,覆盖 UserList 下新类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18791177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com