Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm trying to create a list of objects from the class "fooclass", with different attributes, but always end up with all elements of the list containing the same values.
Here is the code I run:
#!/usr/bin/env python
class fooclass():
def __init__(self,vertices = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]):
self.vertices = vertices
l=[]
print(l)
a=fooclass(); a.vertices[0]=[7,9,9]; l.append(a)
print 'a=', a.vertices
a=fooclass(); a.vertices[0]=[789,9,9]; l.append(a)
print 'a=', a.vertices
print(l[0].vertices)
print(l[1].vertices)
print(l)
l=[]
print(l)
a=fooclass(); a.vertices[0]=[7,9,9]; l.append(a)
print 'a=', a.vertices
b=fooclass(); b.vertices[0]=[789,9,9]; l.append(b)
print 'b=', b.vertices
print(l[0].vertices)
print(l[1].vertices)
print(l[0])
print(l[1])
And the output I get:
$ python ./class_test2.py
[]
a= [[7, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
a= [[789, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[789, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[789, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[<__main__.fooclass instance at 0x7f945eafecf8>, <__main__.fooclass instance at 0x7f945eafed88>]
[]
a= [[7, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
b= [[789, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[789, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[789, 9, 9], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
<__main__.fooclass instance at 0x7f945eafecf8>
<__main__.fooclass instance at 0x7f945eafed88>
Why are l[0].vertices and l[1].vertices exactly the same despite inputting different values?
System info:
Ubuntu 10.04.4 LTS
$ python --version
Python 2.6.5
$ uname -a
Linux *** 2.6.32-39-generic #86-Ubuntu SMP Mon Feb 13 21:50:08 UTC 2012 x86_64 GNU/Linux
Note: Tried with Python 3.1.2 (just changing the print statements), same problem. :(