Objects, lists and assigning values

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 5 13:39:47 EDT 2007


En Thu, 05 Apr 2007 14:13:43 -0300, Manuel Graune <manuel.graune at koeln.de>  
escribió:

> class new_class(object):
>         def __init__(   self,
>                         internal_list=[]):
>                 self.internal_list= internal_list

All your instances share the *same* internal list, because default  
arguments are evaluated only once (when the function is defined)
The usual way is to write:

class new_class(object):
     def __init__(self, internal_list=None):
         if internal_list is None:
             internal_list = []
         self.internal_list= internal_list

See  
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

-- 
Gabriel Genellina




More information about the Python-list mailing list