New instance of a class : not reset?

André andre.roberge at gmail.com
Thu Jan 20 21:46:26 EST 2011


On Thursday, January 20, 2011 10:35:46 PM UTC-4, Jean-Francois wrote:
> 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 = []):

See http://docs.python.org/tutorial/controlflow.html#default-argument-values
Read the text following "Important warning: The default value is evaluated only once.".
André
> 		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 !!!



More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /