How to append Class object to a list without modifying its members?
class Node:
def __init__(self, name, type, children=[]):
self.name = name
self.type = type
self.children = children
def add_child(self, child_node):
self.children.append(child_node)
def printNode(self, indent = 0):
print(self.name + " has children " + str(len(self.children)))
#for child in self.children: print(child, indent + 4)
if __name__ == "__main__":
A = Node("A", "company")
B = Node("B", "department")
B.printNode()
A.add_child(B)
B.printNode()
The append()
function adds node B to itself even though it should only add it to node A's children list, evident from output
B has children 0
B has children 1
You've stumbled onto a very common gotcha when defining arguments to functions in Python. There's a good explanation here.
When you define a function the Python interpreter will create the values that are used as default arguments. These default values are then used for every function call. In this case the empty list children=[]
gets created when __init__
is interpreted. Then the same list is used every time you call add_child()
no matter which object it is called on.
Here's an example:
def my_func(a_list=[]):
a_list.append("something")
print(a_list)
>>> my_func()
["something"]
>>> my_func()
["something", "something"]
In this case a_list
is reused every function call and continues to grow in size.
The way to get around this is to use a different value to signify that the Node should start with an empty list of children. Like so:
class Node:
def __init__(self, name, type, children=None):
self.name = name
self.type = type
self.children = children or []
...