Python script launched. I have a method name as a string. What should I call this method?

everything. See the example below. I would like to provide a string to the sched_action method, which indicates which Bot class method should be called. In the example below, I represented it as "bot.action ()", but I do not know 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')
+5
source share
6 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 accepts an optional argument that allows you to return the default value if the requested action does not exist.

+13
source

Shortly speaking,

getattr(bot, action)()

getattr - . () .

, :

method_to_call = getattr(bot, action)
method_to_call()

:

getattr(bot, action)(argument1, argument2)

method_to_call = getattr(bot, action)
method_to_call(argument1, argument2)
+7

, , , .

class Bot:
    def work(self): 
        print 'working'
    def fight(self): 
        print 'fightin'

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

scheduler = Scheduler()
scheduler.schedule_action(Bot.fight)
scheduler.schedule_action(Bot.work)

:

fightin
working

, , , . , . , - , .

+6
class Scheduler:
    def schedule_action(self,action):
       bot = Bot()
       boundmethod = getattr(bot, action)
       boundmethod()
+3
def schedule_action(self,action):
         bot = Bot()
         bot.__getattribute__(action)()
+1

You can also use a dictionary to map methods to actions. For instance:

ACTIONS = {"fight": Bot.fight,
           "walk": Bot.walk,}

class Scheduler:
    def schedule_action(self, action):
        return ACTIONS[action](Bot())
+1
source

All Articles