Python: Unexpected behavior using contextmanager on class method
This question already has an answer here:
This behavior is due to how mutable default arguments work in Python.
Try changing SymList.__init__()
to the following:
def __init__(self, L=None):
if L is None:
self.L = []
else:
self.L = L
As you modify self.L
in one instance you are also modifying the L
that is passed into SymList.__init__()
, so the result with your code is that all instances would share the same L
attribute when the instance is first initialized.
上一篇: 在Python中默认函数参数的生命周期