Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数名在python类中未定义_Python_Nameerror - Fatal编程技术网

函数名在python类中未定义

函数名在python类中未定义,python,nameerror,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,因此msgname错误:未定义全局名称“

我对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
,因此msg
name错误:未定义全局名称“abc”
当您调用
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

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

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

如果没有
self
关键字,python将在全局范围内寻找
abc
方法,这就是为什么会出现此错误。

它正在工作,类a的函数
abc()
由其实例调用。我认为,您对
b.test()的调用不是
b.abc()
应该抛出错误。这是因为您应该使用类实例的引用调用
abc()
。只需在
test()
中用
self.abc()
替换
abc()