default argument in method
Chris Rebert
clp2 at rebertia.com
Sun Dec 12 06:49:41 EST 2010
On Sun, Dec 12, 2010 at 3:35 AM, 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.
> The obvious solution is put val=None in the signature
> and set val to the appropriate value inside the method
> (if val is None: ...), but I wonder if there's another way.
Nope, not really. There are some more complicated slight variations on
the same theme (e.g. hoisting the idiom into a decorator), but they're
of fairly dubious merit; just use the straightforward idiom you
already outlined.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list