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>]
source
share