I don't understand why the behavior between func_1
and func_2
are different. Intuitively, I thought both shouldn't work, because memory
is initialized each time when the function is called. But apparently there is more to that. And this trick only works for mutable variables (as the list in func_1
). What is going on under the hood here?
class RecursiveDemo:
def func_1(self, memory=[]):
memory.append("@")
if len(memory) <= 5:
self.func_1()
else:
print("=== Done ===")
def func_2(self, memory=0):
memory += 1
if memory <= 5:
self.func_2()
else:
print("=== Done ===")
r = RecursiveDemo()
r.func_1() ## Works. Done is printed.
r.func_2() ## Doesn't work. RecursionError: maximum recursion depth exceeded in comparison