Bug ??

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Eddy Ilg

    #1

    Bug ??

    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,l ink,vars={}):
    self.link=link
    print "vars:",var s
    if hasattr(self,'v ars'):
    print "self.variables :",self.variabl es
    self.variables= vars
    print "self.variables :",self.variabl es

    def set_var(self,na me,value):
    self.variables[name]=value

    [color=blue][color=green][color=darkred]
    >>> from generator import url
    >>> u=url('image')[/color][/color][/color]
    vars: {}
    self.variables: {}[color=blue][color=green][color=darkred]
    >>> u.set_var('a',5 )
    >>> v=url('test')[/color][/color][/color]
    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


  • Mike Meyer

    #2
    Re: Bug ??

    "Eddy Ilg" <eddy@fericom.n et> writes:[color=blue]
    > 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,l ink,vars={}):
    > self.link=link
    > print "vars:",var s
    > if hasattr(self,'v ars'):
    > print "self.variables :",self.variabl es
    > self.variables= vars
    > print "self.variables :",self.variabl es
    >
    > def set_var(self,na me,value):
    > self.variables[name]=value
    >
    >[color=green][color=darkred]
    >>>> from generator import url
    >>>> u=url('image')[/color][/color]
    > vars: {}
    > self.variables: {}[color=green][color=darkred]
    >>>> u.set_var('a',5 )
    >>>> v=url('test')[/color][/color]
    > 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[/color]

    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@mired.or g> http://www.mired.org/home/mwm/
    Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

    Comment

    Working...