7
def do_something(obj, func):
    obj.func()

My question is how do I call func on obj? func is a function of obj. Is this even possible?

bkvaluemeal
  • 428
  • 1
  • 9
  • 23
  • possible duplicate of [Calling a function of a module from a string with the function's name in Python](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) – Ozgur Vatansever Jul 22 '15 at 02:57
  • possible duplicate of [Python - How to invoke an function on an object dynamically by name?](http://stackoverflow.com/questions/3951840/python-how-to-invoke-an-function-on-an-object-dynamically-by-name) – Ozgur Vatansever Jul 22 '15 at 02:57

2 Answers2

5

If func is an actual function of obj you can simply call it:

func()

An example:

class Klass(object):
    def say_hi(self):
        print 'hi from', self

func = Klass().say_hi
func()   # hi from <__main__.Klass object at 0x024B4D70>

Otherwise if func is the name of the function (a string) then this will get it and call it:

getattr(obj, func)()
101
  • 8,514
  • 6
  • 43
  • 69
0

Anyway func is a method defined on obj so you can directly call it using func() not by obj.func() as func itself is obj.func according to your question.

I have cleared this in the below 2 examples executed on Python interactive termainal.

First I have defined a simple class then I have tried to access its instance method according to this question.

>>> # Defining class
... 
>>> class MyClass(object):
...     def __init__(self):
...         self.name = "Rishikesh Agrawani"
...         self.age = 25
...     def doStuff(self):
...         print "DETAILS:\n"
...         print "NAME: %s" % (self.name)
...         print "AGE : %d" % (self.age)
... 
>>> # Instantiation
... 
>>> obj = MyClass()
>>> func = getattr(obj, "doStuff");
>>> func()
DETAILS:

NAME: Rishikesh Agrawani
AGE : 25
>>> 

Finally

>>> def do_something(obj, func):
...     obj.func()
... 
>>> do_something(obj, func)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something
AttributeError: 'MyClass' object has no attribute 'func'
>>> 
>>> def do_something(obj, func):
...     print obj, func
... 
>>> do_something(obj, func)
<__main__.MyClass object at 0x100686450> <bound method MyClass.doStuff of <__main__.MyClass object at 0x100686450>>
>>> 
>>> 
>>> def do_something(obj, func):
...     func()
... 
>>> do_something(obj, func)
DETAILS:

NAME: Rishikesh Agrawani
AGE : 25
>>> 
hygull
  • 8,464
  • 2
  • 43
  • 52