NameError: name 'self' is not defined

前端 未结 3 1918
闹比i
闹比i 2020-11-30 19:52

Why such structure

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

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

gives an error

3条回答
  •  天涯浪人
    2020-11-30 19:56

    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
    

提交回复
热议问题