Bug ??

E

Eddy Ilg

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

vars: {}
self.variables: {}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

Eddy
 
M

Mike Meyer

Eddy Ilg said:
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

vars: {}
self.variables: {}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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,275
Messages
2,571,381
Members
48,070
Latest member
nick_tyson

Latest Threads

Top