Possible duplicate:
least surprise in python: mutable default argument
I want to understand the behavior and consequences of the python __init__ constructor. It seems that when there is an optional parameter, and you are trying to install an existing object on a new object, the additional value of the existing object is saved and copied.
See an example:
In the code below, I'm trying to create a tree structure with nodes and possibly with a lot of children. In the first NodeBad class NodeBad constructor has two parameters: a value and any possible children. The second NodeGood class takes a node value as a parameter. Both have an addchild method to add a child to a node.
When creating a tree with the NodeGood class NodeGood it works as expected. However, doing the same with the NodeBad class, it seems that a child can only be added once!
The code below will lead to the following output:
Good Tree 1 2 3 [< 3 >] Bad Tree 1 2 2 [< 2 >, < 3 >]
Que Pasa?
Here is an example:
#!/usr/bin/python class NodeBad: def __init__(self, value, c=[]): self.value = value self.children = c def addchild(self, node): self.children.append(node) def __str__(self): return '< %s >' % self.value def __repr__(self): return '< %s >' % self.value class NodeGood: def __init__(self, value): self.value = value self.children = [] def addchild(self, node): self.children.append(node) def __str__(self): return '< %s >' % self.value def __repr__(self): return '< %s >' % self.value if __name__ == '__main__': print 'Good Tree' ng = NodeGood(1)
python constructor optional-parameters
christangrant
source share