Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function name is undefined in python class [duplicate]

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
like image 583
aceminer Avatar asked Sep 01 '25 05:09

aceminer


1 Answers

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
like image 130
Paul Lo Avatar answered Sep 02 '25 17:09

Paul Lo