Python脚本正在运行。我有一个方法名作为字符串。我怎么称呼这个方法?

Python脚本正在运行。我有一个方法名作为字符串。我怎么称呼这个方法?,python,Python,各位。请参见下面的示例。我想为'schedule_action'方法提供一个字符串,它指定应该调用什么Bot类方法。在下面的示例中,我将其表示为“bot.action()”,但我不知道如何正确执行。请帮忙 class Bot: def work(self): pass def fight(self): pass class Scheduler: def schedule_action(self,action): bot = Bot() bot

各位。请参见下面的示例。我想为'schedule_action'方法提供一个字符串,它指定应该调用什么Bot类方法。在下面的示例中,我将其表示为“bot.action()”,但我不知道如何正确执行。请帮忙

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')
总之,

getattr(bot, action)()
getattr将按名称查找对象上的属性——属性可以是数据或成员方法,最后的额外
()
调用该方法

您也可以在单独的步骤中获得该方法,如下所示:

method_to_call = getattr(bot, action)
method_to_call()
您可以用通常的方式将参数传递给该方法:

getattr(bot, action)(argument1, argument2)

使用:


注意到GETTATR也有一个可选的参数,它允许您返回默认值,以防请求的动作不存在。

< P>我不确定它是否适用于您的情况,但是您可以考虑使用函数指针而不是操纵字符串。

class Scheduler:
    def schedule_action(self,action):
       bot = Bot()
       boundmethod = getattr(bot, action)
       boundmethod()
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

如果您能做到这一点,那么当代码在编译时而不是在运行时被解释时,它会给您一个关于拼写错误的函数的错误。这可能会缩短愚蠢的数据输入错误的调试周期,特别是如果操作是在一段时间内完成的。没有什么比通宵运行某个程序并在早上发现语法错误更糟糕的了。

您还可以使用字典将方法映射到操作。例如:

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

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

强烈地考虑这个选项。如果您想动态选择要调用的方法,这可能是您的正确选择。如果以某种复杂的方式生成名称(例如从文件、套接字或用户输入中读取名称),则仅使用基于
getattr
的选项。如果为True,则在前面描述的情况下会出现错误,但错误不在编译时出现。
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
ACTIONS = {"fight": Bot.fight,
           "walk": Bot.walk,}

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