Python继承默认值被覆盖

时间:2019-01-09 15:38:10

标签: python oop inheritance

我正在尝试在python中利用继承,但是有一个问题,当未提供famil的值时,名为famil的字段会被先前实例的输入覆盖。

 class Person:
    def __init__(self, famil=[], name="Jim"):
        self._family = famil
        self._name = name

    def get_family(self):
        return self._family

    def get_age(self):
        return self._age


class Woman(Person):
    def __init__(self, family=[], name="Jane"):
        print(family)
        Person.__init__(self, family, name)

    def add_family(self, name):
        self._family += [name]


if __name__ == "__main__":
    a = Woman()
    a.add_family("john")
    print(a.get_family())
    b = Woman()
    print(b.get_family())
    print(a.get_family())

输出:

[]
['john']
['john']
['john']
['john']

预期输出:

[]
['john']
[]
[]
['john']

当我尝试学习继承时,这令人困惑,我认为a和b应该彼此独立。

1 个答案:

答案 0 :(得分:1)

正如注释中提到的,这是一个具有可变默认参数的问题,在Python中无法正常工作。另请参见https://docs.python-guide.org/writing/gotchas/

处理它的最好方法是使默认参数不可更改,如果未提供默认参数,则分配可变的默认值。例如:

class Person:
    def __init__(self, family=None, name="Jim"):
        self._family = family or []
        self._name = name

class Woman(Person):
    def __init__(self, family=None, name="Jane"):
        super().__init__(self, family or [], name)