0

I am trying to utilize inheritance in python but have an issue where, a field named famil is overwritten by the previous instance's input when a value for famil isn't given.

 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())

Output:

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

Expected output:

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

This is confusing as I'm trying to learn inheritance and I thought that a and b should be independent from each other.

Bilal Siddiqui
  • 349
  • 3
  • 17
Jim
  • 3
  • 2

1 Answers1

1

As mentioned in comments, it is an issue with mutable default arguments, which does not work well in Python. See also https://docs.python-guide.org/writing/gotchas/

The best way to deal with it is to make the default argument non-mutable, and if it was not provided assign the mutable default value. E.g.:

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)
mfrackowiak
  • 1,294
  • 8
  • 11