problem manipulating a list belonging to a class

M

Marc Leconte

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

I would have expected

Thanks in advance for advice,
Marc.
 
D

Diez B. Roggisch

Marc said:
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

I would have expected

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

Diez
 
S

Steve Howell

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

Lie Ryan

Marc said:
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?
 
M

Marc Leconte

Thx all, good to know :)

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top