default argument in method

Steve Holden steve at holdenweb.com
Mon Dec 13 12:45:43 EST 2010


On 12/13/2010 12:14 PM, Godson Gera wrote:
> 
> 
> On Sun, Dec 12, 2010 at 5:05 PM, ernest <nfdisco at gmail.com
> <mailto:nfdisco at gmail.com>> wrote:
> 
>     Hi,
> 
>     I'd like to have a reference to an instance attribute as
>     default argument in a method. It doesn't work because
>     "self" is not defined at the time the method signature is
>     evaluated. For example:
> 
>     class C(object):
>        def __init__(self):
>            self.foo = 5
>        def m(self, val=self.foo):
>            return val
> 
>     Raises NameError because 'self' is not defined.
> 
> 
> You can defined foo outside the __init__ and can access it inside
> methods using self.foo
> 
> class C(object):
>      foo=5
>      def __init__(self):
>           print self.foo
>      def m(self,val=foo):
>           return val
> 
> class attributes can be accessed with out self before them in method
> signatures. However, becareful if you change the value of foo inside any
> method, the method signature will still hold on to old value.
> 
You are, of course, correct. It might be more accurate to say that if
C.foo is rebound this does not change the binding of the val default
value. "Change the value of foo" could be though to include "mutate a
mutable value", but in that case both C.foo and the method's val
parameter would still be bound to the same object.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17       http://us.pycon.org/
See Python Video!       http://python.mirocommunity.org/
Holden Web LLC                 http://www.holdenweb.com/




More information about the Python-list mailing list