2015-03-02 342 views
6

我对python比较陌生,我遇到了一些与命名空间有关的问题。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

它正在工作,'class a'的函数'abc()'被其实例调用。 – 2015-03-02 08:06:11

+3

我认为不是'b.abc()',你调用'b.test()'应该抛出错误。这是因为你应该使用类实例的引用来调用'abc()'。只需在'class a'的'test()'函数中用'self.abc()'替换'abc()'。 – 2015-03-02 08:10:35

回答

11

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

为了调用方法来自同一个类,您需要使用self关键字。

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

没有self关键字,Python是寻找一个在全球范围内abc方法,这就是为什么你收到此错误。