[英]RecursionError maximum recursion depth exceeded with an extended class from deque
I implemented an extended class as following.我实现了一个扩展的 class 如下。
from collections import deque
class IntCollection(deque):
def is_empty(self):
return len(self) == 0
def append(self, x):
self.append(x)
And then:接着:
a = IntCollection()
a.is_empty() --> True
Okay, that works.好的,这行得通。 However, when I issued the below command, the RecursionError
occurred:但是,当我发出以下命令时,发生了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)
6
7 def append(self, x):
----> 8 self.append(x)
RecursionError: maximum recursion depth exceeded:
I didn't get the reason why I have this error.我没有得到这个错误的原因。 Anyone can explain?谁能解释一下? I use Python 3.9.4 by the way.顺便说一句,我使用 Python 3.9.4。
You're overriding the deque's append
method.您正在覆盖双端队列的append
方法。 And when you call it it does nothing more than recursively call it again.当你调用它时,它只会递归地再次调用它。 Python has a maximum number of times a function can be called recursively, and after that it gives an error ( RecursionError
). Python 具有可以递归调用 function 的最大次数,然后它会给出错误( RecursionError
)。 Changing the name of the method to something else will work:将方法的名称更改为其他名称将起作用:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.