NameError:名称“ self”未定义

问题:NameError:名称“ self”未定义

为什么这样的结构

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

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

给一个错误NameError: name 'self' is not defined

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?


回答 0

默认参数值在函数定义时评估,但self仅在函数调用时可用。因此,参数列表中的参数不能相互引用。

将参数默认为默认值None并在代码中为此添加测试是一种常见的模式:

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

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

回答 1

对于您还希望将“ b”设置为“无”的情况:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

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

回答 2

如果您通过Google到达这里,请确保检查是否已将self作为类函数的第一个参数。特别是如果您尝试在函数中引用该对象的值。

def foo():
    print(self.bar)

> NameError:名称“ self”未定义

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

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 instance inside the class function.

def foo():
    print(self.bar)

>NameError: name ‘self’ is not defined

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