函数名在python类中未定义
我对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错误:未定义全局名称“
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错误:未定义全局名称“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()
。