python class 中未定义函数名称
function name is undefined in python class
我是 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
为了从同一个 class 调用方法,您需要 self
关键字。
class a:
def abc(self):
print "haha"
def test(self):
self.abc() // will look for abc method in 'a' class
没有 self
关键字,python 正在全局范围内寻找 abc
方法,这就是您收到此错误的原因。
我是 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
为了从同一个 class 调用方法,您需要 self
关键字。
class a:
def abc(self):
print "haha"
def test(self):
self.abc() // will look for abc method in 'a' class
没有 self
关键字,python 正在全局范围内寻找 abc
方法,这就是您收到此错误的原因。