Skip to main content
 首页 » 编程设计

Python:将str格式转换为可调用方法

2025年01月19日10kenshinobiy

我不太清楚要用谷歌搜索什么来找到我的问题的解决方案,所以我会尝试在这里找到它。

我正在使用 pygame 在 Python 3.5.2 中创建一个 Gui。我目前正在处理具有不同按钮功能的错误弹出窗口,具体取决于弹出的错误。我想给出应该作为另一个类中的参数执行的函数。

代码看起来像这样:

def i_want_to_call_this(self): 
  print("Button works.") 
 
def button_with_action(self, action): 
    self.button(self.action) 

另一个类将给出按钮将具有的功能的参数,如下所示:

popup_instance.popup_with_action(i_want_to_call_this) 

但是问题是参数被解析为字符串格式并且不可调用。

请您参考如下方法:

我不知道方法 button 做了什么(我猜它会将作为参数传递的可调用对象绑定(bind)到给定按钮),但您应该考虑使用 getattr , 以便能够使用其名称调用函数,作为字符串传递,如下所示

def button_with_action(self, action): 
    dyn_created_callable = getattr(self, action) 
    self.button(dyn_created_callable) 

当然没有什么能阻止你直接做

def button_with_action(self, action): 
    self.button(getattr(self, action)) 

然后你会用到

#... 
    self.button_with_action('i_want_to_call_this')