<分区>
我是 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
<分区>
我是 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
,所以你看到的那个消息 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
关于python - 函数名称在 python 类中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28805028/