函数名称在python类中未定义

发布于 2021-01-29 19:37:10

我对python相对较新,并且在命名空间方面遇到一些问题。

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

b = a()
b.abc() #throws an error of abc is not defined. cannot explain why is this so
关注者
0
被浏览
116
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    由于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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看