Weird Python behaviour

Jonas Nilsson jmnc at spray.se
Tue Aug 10 07:58:55 EDT 2010


Hello,

Lets say that I want to feed an optional list to class constructor:

class Family():
	def __init__(self, fName, members = []):
		self.fName = fName
		self.members = members

Now, lets add members to two different instances of Family:

f1 = Family("Smith")
f1.members.append("Bill")

f2 = Family("Smithers")
f2.members.append("Joe")

Finally, lets look at the members in the Smithers family:

print f2.members
output: ['Bill', 'Joe']

Why on earth is the output ['Bill', 'Joe']!? Is there a simple  
solution that separates f1 and f2 without forcing me to write code for  
the special case when you don't feed members to the __init__()-function?

/Jonas



More information about the Python-list mailing list