I've been using Python for a very long time. The following has been confusing me today.
Suppose I have this class called Node:
class Node:
def __init__(self, x = []):
self.x = x
a = Node()
b = Node()
a.x.append(3)
b.x.append(5)
To my horror, a.x and b.x both are [3,5]. What is happening here?
Also, how to I stop this from happening? I just want a.x to be [3] and b.x to be [5], not [3,5].
I haven't programmed Python for a while (sadly), but it seems that the problem is that both objects a and b have references to the same object [] rather than distinct new empty lists. Then both append statements are appending to that object.
That is to say that the initialization passes the same object []. The value assigned to the default parameter x (i.e. []) is given as part of the definition of init, not the usage later.
You may need to avoid the default argument in the init to solve it, but there may be other solutions.
Not sure about the following, as I don't have a running system at the moment:
class Node:
def __init__(self, x):
self.x = x
a = Node([])
b = Node([])
etc.