Bug ??
Mike Meyer
mwm at mired.org
Mon Jan 2 20:18:10 EST 2006
"Eddy Ilg" <eddy at fericom.net> writes:
> Hi,
>
> I have a class and I am trying to set the instance varirable 'variables'
> (also tried different names). The variable gets initialized by
> default-value parameter of the constructor. When I change the variable and
> call the constructor again, the default value changes !!! Is this supposed
> to happen? See code and example below:
>
> class url:
> def __init__(self,link,vars={}):
> self.link=link
> print "vars:",vars
> if hasattr(self,'vars'):
> print "self.variables:",self.variables
> self.variables=vars
> print "self.variables:",self.variables
>
> def set_var(self,name,value):
> self.variables[name]=value
>
>
>>>> from generator import url
>>>> u=url('image')
> vars: {}
> self.variables: {}
>>>> u.set_var('a',5)
>>>> v=url('test')
> vars: {'a': 5}
> self.variables: {'a': 5}
>
> See that 'vars' gets the old value of 'variables' passed? How can this be???
> I am using python version 2.3.5
This is a FAQ. Default arguments are evaluated when the function is
*defined*, not when it's called. To get the behavior you want, write:
def __init__(self, link, vars = None):
if not vars:
vars = {}
...
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list