来自 deque

问题描述

我实现了一个扩展类,如下所示。

from collections import deque

class IntCollection(deque):
    def is_empty(self):
        return len(self) == 0

    def append(self,x):
        self.append(x)

然后:

a = IntCollection()
a.is_empty() --> True

好的,那行得通。但是,当我发出以下命令时,RecursionError 发生了:

a.append(1)

RecursionError                            Traceback (most recent call last)
<ipython-input-104-da0a5ad497c3> in <module>
----> 1 a.append(1)

<ipython-input-101-7eac8c051433> in append(self,x)
      6 
      7     def append(self,x):
----> 8         self.append(x)

... last 1 frames repeated,from the frame below ...

<ipython-input-101-7eac8c051433> in append(self,x):
----> 8         self.append(x)

RecursionError: maximum recursion depth exceeded:

我不明白出现此错误的原因。谁能解释一下?顺便说一下,我使用的是 Python 3.9.4。

解决方法

您正在覆盖双端队列的 append 方法。当你调用它时,它只会递归地再次调用它。 Python 有一个函数可以被递归调用的最大次数,之后它会给出错误(RecursionError)。 将方法的名称更改为其他名称即可:

from collections import deque

class IntCollection(deque):
    def is_empty(self):
        return len(self) == 0

    def update(self,x):  # <-- change this name
        self.append(x)
        
a = IntCollection()
# now this work fine
a.update(1)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...