32

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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
aceminer
  • 4,089
  • 9
  • 56
  • 104
  • It is working, the function `abc()` of `class a` is called by its instance. – Vivek Sable Mar 02 '15 at 08:06
  • 3
    I think instead of `b.abc()`, yours call to `b.test()` should be throwing the error. And that's because you should be calling `abc()` with the reference of the class instance. Simply replace `abc()` with `self.abc()` in `test()` function of `class a`. – Moinuddin Quadri Mar 02 '15 at 08:10

2 Answers2

59

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
Paul Lo
  • 6,032
  • 6
  • 31
  • 36
28

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.

G5W
  • 36,531
  • 10
  • 47
  • 80
Beri
  • 11,470
  • 4
  • 35
  • 57