Python继承默认值被覆盖

2024-06-01 20:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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应该相互独立。你知道吗


Tags: nameselfaddagegetreturninitdef
1条回答
网友
1楼 · 发布于 2024-06-01 20:17:36

正如在注释中提到的,这是一个可变默认参数的问题,在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)

相关问题 更多 >