Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script is running. I have a method name as a string. How do I call this method?

Tags:

python

everyone. Please see example below. I'd like to supply a string to 'schedule_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea how to do it correctly. Please help

class Bot:
    def work(self): pass
    def fight(self): pass

class Scheduler:
    def schedule_action(self,action):
       bot = Bot()
       bot.action()

scheduler = Scheduler()
scheduler.schedule_action('fight')
like image 743
facha Avatar asked Feb 26 '10 19:02

facha


People also ask

How do you call a method from a string in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.

How do you read a function name in Python?

Use the __name__ Property to Get the Function Name in Python In Python, every single function that is declared and imported in your project will have the __name__ property, which you can directly access from the function.

How do I turn a string into a function name?

String To Function Using The eval() Function In Python We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ' () ' separated by the addition symbol ' + '.


1 Answers

Use getattr:

class Bot:
    def fight(self):
       print "fighting is fun!"

class Scheduler:       
    def schedule_action(self,action):
       bot = Bot()
       getattr(bot,action)()

scheduler = Scheduler()
scheduler.schedule_action('fight')

Note that getattr also takes an optional argument that allows you to return a default value in case the requested action doesn't exist.

like image 131
Mark Byers Avatar answered Nov 15 '22 00:11

Mark Byers