-4

I receive a string, for example "save". And i have a method save with paramethers. How can i convert the string save in a call to save(). I tried with eval and exec.

Edit: Solved here --> Calling a function of a module from a string with the function's name in Python

Community
  • 1
  • 1
Daniel Ruiz
  • 49
  • 1
  • 3
  • "*I tried with eval and exec*" and then what happened? – Ashwini Chaudhary Apr 22 '14 at 11:47
  • 1
    don't use eval or exec. use `getattr` on the object which has the method. – wim Apr 22 '14 at 11:49
  • Where's this "save" string coming from? User input? If so, you're not going to want code that directly calls the method with that name. What happens if you want to change the user interface? Do you rename your method "s" if the save command becomes "s"? What if it's "Save Your Progress"? – user2357112 Apr 22 '14 at 11:55

1 Answers1

0
def some_method(self):
    save_method = getattr(self, 'save')
    save_method()  # save()
Maciej Gol
  • 15,394
  • 4
  • 33
  • 51