This is a more a question to gain an understanding. Consider the code below
class MenuItem:
def __init__(self, title, children = []):
self.title = title
self.children = children
item1 = MenuItem('A')
item2 = MenuItem('B')
item2.children.append('C')
print (item1.children)
When run with either python2 or python3:
python test.py [~]
['C']
In this case, the children for an object, defaults to the empty list. children = []
. However, if I create two objects, they share the same children list.
I understand that object based types are just a pointer to a more complex object etc, but I don't understand what exactly []
is pointing to. If I change item2.title
, that has no effect on item1.title
.
If I change the default item to ['X']
for example, I get item1.children = ['X', 'C']
Could someone please explain this behaviour.
Thanks
Anthony
note: The solution is simply to say children = False
and self.children = (children if children else []
which then works as expected - I'm just wondering why the behaviour is as above.