Setting Class Attributes
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Tue Oct 25 16:54:00 EDT 2005
the.theorist a écrit :
> I have a small, simple class which contains a dictionary (and some
> other stuff, not shown). I then have a container class (Big) that holds
> some instances of the simple class. When I try to edit the elements of
> the dictionary, all instances obtain those changes; I want each
> instance to hold separate entries.
>
> #----------Begin module test.py
> class ex:
class ex(object): # oldstyle classes are deprecated
> def __init__(self, val={}):
> self.value = val
You didn't search very long. This is one of the most (in)famous Python
gotchas: default args are evaluated *only once*, when the function
definition is evaluated (at load time). This is also a dirty trick to
have a 'static' (as in C) like variable.
The solution is quite simple:
class ex(object):
def __init__(self, val=None):
if val is None: val = {}
self.value = val
(snip)
More information about the Python-list
mailing list