I implemented an extended class as following.
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:
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.
You're overriding the deque's append
method. 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
).
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)