I am relatively new to python and i am experiencing some issues with namespacing.
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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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:
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
Method 2
In order to call method from the same class, you need the self keyword.
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0