New instance of a class : not reset?

J

Jean-Francois

Hi,

In the following example, I don't understand why attribute 'data' is
not reset when I get the new instance of Bag
It works if I make a copy (data[:]) but I want to understand why

Thanks


class Bag(object):
def __init__(self, data = []):
self.data = data
#self.data = data[:]
def add(self, x):
self.data.append(x)

bag = Bag()
print bag.data
bag.add('toto')
print bag.data
bag = Bag() # new instance of Bag, all attributes clear?
print bag.data # 'toto' is still there !!!
 
M

MRAB

Hi,

In the following example, I don't understand why attribute 'data' is
not reset when I get the new instance of Bag
It works if I make a copy (data[:]) but I want to understand why

Thanks


class Bag(object):
def __init__(self, data = []):
self.data = data
#self.data = data[:]
def add(self, x):
self.data.append(x)

bag = Bag()
print bag.data
bag.add('toto')
print bag.data
bag = Bag() # new instance of Bag, all attributes clear?
print bag.data # 'toto' is still there !!!

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

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top