我对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
由于test()不知道是谁abc,因此NameError: global name 'abc' is not defined您看到的味精应该在调用时发生b.test()(调用b.abc()很好),请将其更改为:
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