0

I am learning Python. I want to call a function from a String. I made a sample program for this.

class Calling:
    def __init__(self,a):
        self.Callto(a)
    def Callto(self,a):
        re=self.Hello(a)    
        print "Calling= "+re    # Here L= CallMe
        self.re()               # Error is in this line 
    def Hello(self,a):
        b="Me"
        return a+b  
    def CallMe():
        print "I am Called"

x=Calling("Call")

Traceback: AttributeError: Calling instance has no attribute 're'

So far what I got is I cant call function with string. What can I do to make this string ('re') callable? Thanks for reading

Sam
  • 79
  • 2
  • 10
  • 2
    Why are you doing this? – Veedrac Dec 30 '13 at 05:13
  • I have another program which will take string value by opening txt file and call one by one... but that program is very big to share... So I made a sample problem... – Sam Dec 30 '13 at 05:16

1 Answers1

1

You can feed the function to a dict and call it from there.

>>> def foo():
        print 'foo'



>>> def bar():
        print 'bar'


>>> funcs = {
             'foo':foo,
             'bar':bar
            }
>>> funcs['foo']()
foo
>>> funcs['bar']()
bar
>>> 
Grim Reaper
  • 550
  • 1
  • 5
  • 18
  • This is a good answer, But If I could write 'foo':foo dynamically then that would be great. In my program I shall get a string named foo from a txt file and I will have to call foo.. So for me there is no option to write funcs{ 'All my functions'} manually.. – Sam Dec 30 '13 at 09:42
  • If your using a class/module you can use getattr function. – Grim Reaper Dec 30 '13 at 16:45