tags:

views:

835

answers:

2

Why such structure

class A:
    def __init__(self, a):
        self.a = a

    def p(self, b=self.a):
        print b

gives an error NameError: name 'self' is not defined?

+13  A: 

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b
intgr
A: 

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b
Andrew
Can't you think up more complicated solution?
valya
Not sure what's overly complicated about it. Feel free to chime in with your own solution that preserves all values of b.
Andrew