python - 函数名称在 python 类中未定义

标签 python nameerror

<分区>

我是 python 的新手,我遇到了一些命名空间问题。

class a:
    def abc(self):
        print "haha" 
    def test(self):
        abc()

b = a()
b.test() #throws an error of abc is not defined. cannot explain why is this so

最佳答案

因为 test() 不知道谁是 abc,所以你看到的那个消息 NameError: global name 'abc' is not defined应该在调用 b.test() 时发生(调用 b.abc() 没问题),将其更改为:

class a:
    def abc(self):
        print "haha" 
    def test(self):
        self.abc()  
        # abc()

b = a()
b.abc() #  'haha' is printed
b.test() # 'haha' is printed

关于python - 函数名称在 python 类中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28805028/

相关文章:

python - 如何从数据库查询中删除列表中的嵌套列表?

python - 计算Python中两个链接列的频率

python - 在 python 中,如何将 CSV 文件的列写入字典?

python - NameError:名称 'first' 未定义

Python:实现一系列函数,每个函数调用下一个函数

python - 如何按主色自动分类图像?

python - 用Python编写音频插件

python - pylint_django 抛出异常

python - Python 3.6 中的名称错误

即使我导入了集合,也没有定义 python 全局名称 'collections'