Unexpected default arguments behaviour (Maybe bug?)

marek.rocki at wp.pl marek.rocki at wp.pl
Sun Jul 13 13:42:17 EDT 2008


sukkop... at gmail.com napisał(a):
> Hi, I have just encountered a Python behaviour I wouldn't expect. Take
> the following code:
>
> ------------------------------------------------------------------------
> class Parent:
>     a = 1
>
>     def m (self, param = a):
>         print "param = %d" % param
>
> class Child (Parent):
>     a = 2
>
>
> p = Parent ()
> p.m ()
>
> c = Child ()
> c.m ()
> ------------------------------------------------------------------------
>
> I would expect to receive the following output:
> param = 1
> param = 2
>
> But actually I get:
> param = 1
> param = 1
>
> Is this the correct behaviour, and then why, or is it a bug? For
> reference, I am using Python 2.5.1 on UNIX.
>
> Thanks in advance!

I expect it's because default values for parameters are evaluated and
bound at definition time. So once "def m (self, param = a):" line
executes, the default value for parameter is forever bound to be 1.
What you can do is for example:

>     def m (self, param = None):
>         if param is None: param = self.a
>         print "param = %d" % param

Regards,
Marek



More information about the Python-list mailing list