The Python Add to Instance List item also adds it to another instance list.

Possible Duplicate:
“Least Surprise” in Python: Argument Argument Allowed by Argument

I created a Person class that has a name and a list of children. Children of the same class Persons. If I create two instances of Person and add the child to one of the person instances, it is added to both instances of Person. I suppose that a child should be added only to the children of person1, and not to person2, but it is added to both. I have to do something obvious wrong, but I do not see it.

Similar questions showed that people added the definition of the variable to the class itself instead of the constructor, but this is not what happens here. Any help would be greatly appreciated, it fries my brain!

See below code and output:

class Person(object):

    def __init__(self, name, children=[]):
        self.name = name
        self.children = children

    def __repr__(self):
        return '<' + self.name + '>'

    def add_child(self, child):
        self.children.append(child)


def main():
    person1 = Person('Person1')
    person2 = Person('Person2')

    person1.add_child(Person("Person 1 child"))

    print "Person 1 children:", person1.children
    print "Person 2 children:", person2.children

if __name__ == "__main__":
    main()

output of this code:

Person 1 children: [<Person 1 child>]
Person 2 children: [<Person 1 child>]
+5
source share
2 answers

The problem is the default value of the parameter children. If you use a mutable object (such as a list) and initialize it in the header, it will be initialized only once, and then will be used in all instances.

This was discussed here .

Try replacing

def __init__(self, name, children=[]):
    self.name = name
    self.children = children

with

def __init__(self, name, children=None):
    self.name = name
    if children is None:
        self.children = []
    else:
        self.children = children
+7
source

For your init, use instead:

def __init__(self, name, children=None):
    self.name = name
    if children is None:
        self.children = []
    else:
        self.children = children

, Two Person ( , , ). .

+1

All Articles