Here is some code (Python 2.7):
class Test:
@staticmethod
def BuildSample():
rootItem = Test('root')
childA = Test('ChildA')
rootItem.AppendChildren([childA])
childA.AppendChildren([Test('Child' + str(i)) for i in range(3)])
return rootItem
def __init__(self, name):
self.name = name
self.children = []
def AppendChildren(self, items):
self.children.extend(items)
def GetChildren(self):
return self.children
def GetName(self):
return self.name
sample = Test.BuildSample()
print 'sample.GetName() = ' + sample.GetName()
print 'sample.GetChildren() has ' + str(len(sample.GetChildren())) + ' children.'
print 'childA.GetName() = ' + sample.GetChildren()[0].GetName()
print 'childA.GetChildren() has ' + str(len(sample.GetChildren()[0].GetChildren())) + ' children.'
Here is the output:
sample.GetName() = root
sample.GetChildren() has 1 children.
childA.GetName() = ChildA
childA.GetChildren() has 3 children.
This is what I would expect. Now, if I change the code above by replacing the constructor with this version:
def __init__(self, name, children=[]):
self.name = name
self.children = children
... I get the following output:
sample.GetName() = root
sample.GetChildren() has 4 children.
childA.GetName() = ChildA
childA.GetChildren() has 4 children.
What's happening is that the Child0, Child1, and Child2 items are being added to the children list of BOTH the root item AND the childA item.
My question is, why? What is the semantic difference between these two methods when the optional children parameter isn't given?