0

For some reason children is static in this situation even though I'm declaring it as an instance variable. Currently using python 3.7.5

class Node:
    def __init__(self, value, children=list()):
        self.value = value
        self.children = children

    def add_child(self, child):
        self.children.append(child)
a = Node(1)
b = Node(2)
a.add_child(b)

What will happen in this situation is that a.children and b.children will be the same. But, I thought that if I used self.children = that the member would be part of the instance and not the class. I thought that children would only be static if it was declared like this:

class Node:
    children = list()
  • 2
    " I thought that if I used self.children = that the member would be part of the instance" => this is indeed the case - your issue is with the infamous mutable default argument gotcha, as explained in the dup. – bruno desthuilliers Mar 24 '20 at 06:45
  • 1
    Downvoting this question is harsh. it is apparent that this is surprising behavior, and that many people new to the language are very much surprised by it, and it may not be obvious what to search for. This question provided a [mcve], so it's miles ahead of a lot of questions. – juanpa.arrivillaga Mar 24 '20 at 07:04

0 Answers0