-1

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Unexpected connections between class instances

here is my code to build a class called Neuron:

class Neuron():
  def __init__(self,connection=[]):
      self.connection=connection
  def makeConnection(self,other):
      self.connection.append(other)
  def getConnection(self):
      return self.connection

as you see each object of this class has it's own connection to other objects of the same class. Now i build a group of Neurons :

P=[]
for i in range(5):
   P.append(Neuron())

Now , i want to make connections between my neurons: let's do something simple:

 P[1].makeConnection(P[2])

now when i check in python :

 P[2].getConnection()

it gives me P[2] in it's connection list! i just applied makeConnection method on P[1], where on earth I connected P[2] to itself!?! please someone help!

Community
  • 1
  • 1
Sun
  • 11
  • 3

1 Answers1

3

Change

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

to

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

Otherwise all your objects end up referring to the same list. When you change one neuron's connections, all other neurons change too.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • wow... that was great! i couldn't figure it out ! but how come connection=[] does not mean empty list. i thought it would make a new empty list for each object...i know where things went wrong but now i'm confused! :) thank you ! – Sun Nov 26 '12 at 12:08
  • @Sun: It makes a new list once, when the function is defined, and keeps using that list over and over again. It does not make a new list every time you call the function. – NPE Nov 26 '12 at 12:09
  • 2
    @Sun: Spending two minutes reading the question we linked you to would have solved this for you as well. – Martijn Pieters Nov 26 '12 at 12:11