Python base classes share attributes?

This question already has an answer here:

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

  • You're making a common Python newcomer mistake.

    See my answer here: How should I declare default values for instance variables in Python?

    Briefly explained, Python interprets the class definitions only once . That means everything declared in the __init__() method is only created once. Or, in another words, your [] list default argument is only made once.

    Then self.l = l assigns a reference to the same instance every time you create a new class, hence the behaviour you weren't expecting.

    The Pythonic way is this (partial code):

    def __init__(self, arg=None):
        if arg is None:
            arg = []
        self.arg = arg
    

    Also, you should consider using a better naming convention than l , which is hard to read and might be mistaken as 1 or | .


    This is called the mutable default argument bug that is commonly made by people new to Python. When you give a mutable as a default argument, the same object gets used across instances when the default argument is required to be used. The get a better understand check the Important warning section in http://docs.python.org/tutorial/controlflow.html#default-argument-values

    In your code, the instance a used the mutable default argument (a empty list object) in it's init call and when you created the instance of b, which in turn called Base's init method, again used the very same object that a used in it's init. On simpler words al and bl point to the same list object.

    A very similar discussion - "Least Astonishment" and the Mutable Default Argument

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

    上一篇: 函数参数中一个空列表的值,例如这里

    下一篇: Python基类共享属性?