Setting Class Attributes

the.theorist the.theorist at gmail.com
Tue Oct 25 18:57:41 EDT 2005


Bruno Desthuilliers wrote:
> 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)

Hey, that was extremely helpful. I suspect that the default args
evaluation is optimized for speed. So it makes sense to use the None
assignment, and a test condition later.

Worked like a charm, Thanks!




More information about the Python-list mailing list