Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

problem manipulating a list belonging to a class

0 views
Skip to first unread message

Marc Leconte

unread,
Nov 22, 2009, 5:50:43 PM11/22/09
to pytho...@python.org
Dear all,

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.

Diez B. Roggisch

unread,
Nov 22, 2009, 6:10:19 PM11/22/09
to
Marc Leconte schrieb:

http://effbot.org/zone/default-values.htm

Diez

Steve Howell

unread,
Nov 22, 2009, 6:14:00 PM11/22/09
to
On Nov 22, 2:50 pm, Marc Leconte <marcg...@free.fr> wrote:
> Dear all,
>
> 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
>

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...

Steve Howell

unread,
Nov 22, 2009, 6:16:42 PM11/22/09
to
On Nov 22, 3:14 pm, Steve Howell <showel...@yahoo.com> wrote:

> 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

Lie Ryan

unread,
Nov 22, 2009, 10:55:28 PM11/22/09
to
Marc Leconte wrote:
> class Toto(object):
> def __init__(self, number, mylist=[]):
> self.number=number
> self.mylist=mylist
> pass
> pass

Why are you using pass to end your blocks?

Terry Reedy

unread,
Nov 23, 2009, 4:43:01 AM11/23/09
to pytho...@python.org
Marc Leconte wrote:
> Dear all,
>
> 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,

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.

Marc Leconte

unread,
Nov 23, 2009, 1:47:22 PM11/23/09
to Steve Howell, pytho...@python.org
Thx all, good to know :)

Le dimanche 22 novembre 2009 ᅵ 15:16 -0800, Steve Howell a ᅵcrit :

0 new messages