Python: Unexpected behavior using contextmanager on class method

This question already has an answer here:

  • “Least Astonishment” and the Mutable Default Argument 30 answers
  • Python constructor and default value [duplicate] 4 answers

  • 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.

    链接地址: http://www.djcxy.com/p/28538.html

    上一篇: 在Python中默认函数参数的生命周期

    下一篇: Python:在类方法上使用contextmanager的意外行为