本文介绍了函数名在python类中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 比较陌生,我在命名空间方面遇到了一些问题.

I am relatively new to python and i am experiencing some issues with namespacing.

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,所以 msg NameError:全局名称 'abc' 未定义 您看到应该在调用 b.test() 时发生(调用 b.abc() 很好),更改它:

Since test() doesn't know who is abc, that msg NameError: global name 'abc' is not defined you see should happen when you invoke b.test() (calling b.abc() is fine), change it to:

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类中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:08