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
Radheya
  • 779
  • 1
  • 11
  • 41

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
  • 278,196
  • 72
  • 453
  • 469
  • sorry I totally missed it. thanks for answer and edit. I understood what and why it was not working. – Radheya 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
  • 82,630
  • 20
  • 166
  • 161