函数名在python类中是未定义的

ace*_*ner 13 python undefined

我是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
Run Code Online (Sandbox Code Playgroud)

Pau*_* Lo 24

既然test()不知道是谁abc,NameError: global name 'abc' is not defined你看到的msg 应该在你调用时发生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
Run Code Online (Sandbox Code Playgroud)


Ber*_*eri 12

要从同一个类调用方法,您需要self关键字.

class a:
    def abc(self):
        print "haha" 
    def test(self):
        self.abc() // will look for abc method in 'a' class
Run Code Online (Sandbox Code Playgroud)

没有self关键字,python正在abc全局范围内寻找方法,这就是你得到这个错误的原因.