I have a problem with the following code (ubuntu 8.04, Python 2.5.2):
class Toto(object):
def __init__(self, number, mylist=[]):
self.number=number
self.mylist=mylist
pass
pass
listA=Toto(number=1)
listB=Toto(number=2)
listA.mylist.append(5)
print "1) ", listA.mylist
print "2) ", listB.mylist
>> 1) [5]
>> 2) [5]
I would have expected
>> 1) [5]
>> 2) []
Thanks in advance for advice,
Marc.
Change your code to do this:
def __init__(self, number, mylist=None):
if mylist is None:
self.mylist = []
else:
self.mylist = mylist
Explanations of why you need to write it that will follow...
> Explanations of why you need to write it that will follow...
I knew this had to be written up somewhere...
http://www.ferg.org/projects/python_gotchas.html#contents_item_6
Why are you using pass to end your blocks?
Read the Python FAQ and or the reference manual section on def
statements (function definition) which specifically has a paragraph with
a bold-face statement explaining this.
Le dimanche 22 novembre 2009 ᅵ 15:16 -0800, Steve Howell a ᅵcrit :