1

I want to fetch function with function name string eg.

class test(object):
  def fetch_function():
    print "Function is call"

 #now i want to fetch function  using  string 
 "fetch_function()"

Result should be: Function is call

4
  • You could use eval: eval("fetch_function()") It's not too safe tho, it opens a route for many hackers. Commented Jun 18, 2013 at 9:25
  • @ Markus Meskanen : thanx for answer but my issue is that string fix "fetch_function()" i dont want to make any change in that in that case your solution is not work. Commented Jun 18, 2013 at 9:27
  • @Heroic You should then clarify your question. What shouldn't be changed? If the string must just stand in your code as it does currently there can't be done very much Commented Jun 18, 2013 at 9:38
  • I have already mention in my question that i want to fetch using string "fetch_function()". Commented Jun 18, 2013 at 10:04

3 Answers 3

4

If you would leave the () from fetch_function() you could use getattr which is in my opinion safer than eval:

class Test(object):

    def fetch_function():
        print "Function is called"

test_instance = Test()
my_func = getattr(test_instance, 'fetch_function')

# now you can call my_func just like a regular function:
my_func()
Sign up to request clarification or add additional context in comments.

2 Comments

And if you need to call the method only once, there's no need for the variable: getattr(inst, "fetch_function")()
@rednaw : Thanx for your answer ,but i cant leave ().
1

Use eval():

eval("fetch_function()")

Comments

0

As said eval is not safe, you could use a dict to map a function to a string and call it

class test(object):
  dict_map_func = {'fetch_f': fetch_function}
  def fetch_function():
     print "Function is call"


test.dict_map_func['fetch_f']()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.