default argument in method

Godson Gera godson.g at gmail.com
Mon Dec 13 12:14:27 EST 2010


On Sun, Dec 12, 2010 at 5:05 PM, ernest <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.

-- 
Thanks & Regards,
Godson Gera
Python Consultant India <http://godson.in>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101213/638e0ccc/attachment.html>


More information about the Python-list mailing list