python - NameError:名称“ self”未定义

original title: "python - NameError: name 'self' is not defined"


Translate

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?



为什么这样的结构类A:def __init __(self,a):self.a = def p(self,b = self.a):print b给出错误NameError:名称'self'未定义?

这是翻译后的摘要,如果您需要查看完整的翻译,请单击“Translate”图标


所有的回答
  • Translate

    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
    

  • Translate

    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
    

  • Translate

    If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object inside the function.

    def foo():
        print(self.bar)
    

    >NameError: name 'self' is not defined

    def foo(self):
        print(self.bar)
    

    >"Congrats you got rid of the NameError!"