1

When I try to alter a class attribute in a particular instance, the attributes of all the other instances change, too. Even when I create a brand new instance of the class, its attributes are automatically changed

I'm trying to implement a tree-type data structure. I think the problem has something to do with inheritance, but I can't figure it out.


#here I'm making a simple class to represent
#the node of a tree
class Node:

    def __init__(self, children=[]):
        self.children = children

root = Node()
branch = Node()

#now I make branch a child of root
root.children.append(branch)

#and it works...
root.children
>>>[<pexp2.Node object at 0x7f30146d3438>]

#...but for some reason branch now also has a child
branch.children
>>>[<pexp2.Node object at 0x7f30146d3438>]

#and now I make a whole new instance that
#isn't connected to root or branch
isolated_node = Node()

#and somehow it also has a child that I never gave it
isolated_node.children
>>>[<pexp2.Node object at 0x7f30146d3438>]

I don't know why every node is getting a child. I only want a Node to have children if I specify that it should. In the above code, root is the only one that should have a child (or that's what I thought).

ytu bien
  • 35
  • 4
  • even though this has been marke as duplicate, I have added an answer considering you are quite new to Stack Overflow. I hope it helps, and please let me know if you need further explanations. – lmiguelvargasf Jul 12 '19 at 02:07

1 Answers1

2

You are facing what is known as Mutable Default Argument, try the following:

class Node:

    def __init__(self, children=None):
        if children is None:
            children = []
        self.children = children

Basically, you are having this problem because:

  • a function declaration is executed only once, creating all default value objects
  • everything is passed by reference
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228