0

I am on python 2.7 and trying to call a member function from another function which is located within same class.

class Foo:
     
     def bar(self):
         print 'correctly called'
         
     def baz(self):
         self.bar
    
  
a = Foo()
a.baz()

I went through this question and wrote a sample class as above, but still not able to print "correctly called" located in function bar. This may sound little noob but I think this is the only way to call a member function or am I doing anything wrong?

What I want

I simply want to call print statement located in bar function from another member function baz within same class.

Community
  • 1
  • 1
Dhruvify
  • 647
  • 1
  • 9
  • 30

2 Answers2

2

To call a function, employ parentheses:

class Foo:
     def bar(self):
         print('correctly called')

     def baz(self):
         self.bar() # <-- ()

When you write self.bar, this is an expression evaluating to a function object. This is useful if you want to pass the function object to map and the like.

phihag
  • 263,143
  • 67
  • 432
  • 458
  • sorry I totally missed it. thanks for answer and edit. I understood what and why it was not working. – Dhruvify Dec 08 '15 at 10:37
1

Call a method with ():

self.bar()

self.bar is the access to this object. Need the parentheses to actually call it.

Mike Müller
  • 77,540
  • 18
  • 155
  • 159