函数名在python类中未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28805028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
function name is undefined in python class
提问by aceminer
I am relatively new to python and i am experiencing some issues with namespacing.
我对 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
采纳答案by Paul Lo
Since test()
doesn't know who is abc
, that msg NameError: global name 'abc' is not defined
you see should happen when you invoke b.test()
(calling b.abc()
is fine), change it to:
由于test()
不知道 who is 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
回答by Beri
In order to call method from the same class, you need the self
keyword.
为了从同一个类调用方法,你需要self
关键字。
class a:
def abc(self):
print "haha"
def test(self):
self.abc() // will look for abc method in 'a' class
Without the self
keyword, python is looking for the abc
method in the global scope, that is why you are getting this error.
如果没有self
关键字,python 会abc
在全局范围内查找该方法,这就是您收到此错误的原因。