Function name undefined in python class

I am relatively new to python and I am experiencing some problems with namespacing.

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 
+6
source share
2 answers

Since test() does not know who abc , msg NameError: global name 'abc' is not defined , which you see should happen when you call b.test() (calling b.abc() is ok) 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 
+11
source

To call a method from the same class, you need the 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 searches for the abc method in the global scope, so you get this error.

+7
source

Source: https://habr.com/ru/post/983202/


All Articles