1

I created a node class like this:

  def __init__(self, data, incoming = [], outgoing = []):
    self.data = data
    self.incoming = incoming
    self.outgoing = outgoing

  def addIncoming(self, incoming):
    self.incoming.append(incoming)

  def addOutgoing(self, outgoing):
    self.outgoing.append(outgoing)

where every instance was initialized like Node(number) so the incoming and outgoing parameters were defaulted to an empty list. I also had functions that appended other nodes to the incoming and outgoing list but when I did that, it was appending to every instance. For example lets say I had a=Node(1) and b=Node(2). If I did a.addIncoming(b) and printed a.incoming and b.incoming, they both would print Node b. Why are these values shared between separate instances?

When I updated my init function to be

  def __init__(self, data, incoming = [], outgoing = []):
    self.data = data
    self.incoming = []
    self.outgoing = []

everything worked as expected but I feel like the two should work the same. What am I misunderstanding here?

10
  • 2
    This has nothing to do with a class. Default parameter values are only evaluated once. This means that [] there creates only one list object for all function calls and object instances. Commented Jul 27, 2020 at 16:54
  • There are enough differences between this question and the linked duplicate that I thought it deserved to remain open. Commented Jul 27, 2020 at 16:58
  • Dang, I keep forgetting the dupe-hammer works in both directions. Commented Jul 27, 2020 at 16:59
  • Read Default Parameter Values in Python. Commented Jul 27, 2020 at 17:10
  • 1
    @MarkRansom what "differences"? It's exactly the same problem, and has been covered in great detail on the canonical post. Commented Jul 27, 2020 at 17:10

1 Answer 1

3

Default parameters are evaluated when the function is defined, and stored with the function. So __init__ gets those empty lists, but every time you modify them the modifications are saved.

Remember that in Python, making new assignments with = does not make a copy of the data. Those lists are shared with every assignment you make.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.