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')
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.
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.
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 ' + '.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With