Python脚本正在运行。我有一个方法名称作为字符串。我该如何称呼此方法?

StackOverflow https://stackoverflow.com/questions/2344212

  •  23-09-2019
  •  | 
  •  

每个人。请参阅下面的示例。我想为指定的“ 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:

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')

请注意,GetAttr还采用一个可选的参数,该参数允许您返回默认值,以防所请求的操作不存在。

其他提示

简而言之,

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)

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

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

如果您可以做到这一点,它将为您提供有关拼写错误功能的错误 在编译时 解释代码而不是在运行时进行解释时。这可能会缩短您的调试周期,以获取愚蠢的数据输入错误,尤其是如果这些操作在时间范围内完成的情况下。没有什么比一夜之间运行的东西更糟糕的了,发现您早上遇到了语法错误。

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

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

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

class Scheduler:
    def schedule_action(self, action):
        return ACTIONS[action](Bot())
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top