簡體   English   中英

Python腳本正在運行。我有一個方法名稱作為字符串。我該如何調用此方法?

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

大家。 請參閱下面的示例。 我想為'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將按名稱查找對象的屬性 - 屬性可以是數據或成員方法最后的extra ()調用該方法。

您可以在單獨的步驟中獲取該方法,如下所示:

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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM