NameError:名称"self"未定义 [英] NameError: name 'self' is not defined

查看:195
本文介绍了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?

推荐答案

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

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.

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

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

这篇关于NameError:名称"self"未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆