Python: 将 str 格式转换为可调用方法
Python: Convert str format to callable method
我不太清楚如何google找到解决我的问题的方法,所以我会尝试在这里找到它。
我正在使用 pygame 在 Python 3.5.2 中创建一个 Gui。我目前正在处理具有不同按钮功能的错误弹出窗口,具体取决于弹出的错误。我想在另一个 class.
中给出应该作为参数执行的函数
代码看起来像这样:
def i_want_to_call_this(self):
print("Button works.")
def button_with_action(self, action):
self.button(self.action)
另一个 class 将给出按钮将具有的功能的参数,如下所示:
popup_instance.popup_with_action(i_want_to_call_this)
但是问题是参数被解析为字符串格式并且不可调用。
我不知道方法 button
的作用(我猜它会将作为参数传递的可调用对象绑定到给定按钮),但您应该考虑使用 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')
我不太清楚如何google找到解决我的问题的方法,所以我会尝试在这里找到它。
我正在使用 pygame 在 Python 3.5.2 中创建一个 Gui。我目前正在处理具有不同按钮功能的错误弹出窗口,具体取决于弹出的错误。我想在另一个 class.
中给出应该作为参数执行的函数代码看起来像这样:
def i_want_to_call_this(self):
print("Button works.")
def button_with_action(self, action):
self.button(self.action)
另一个 class 将给出按钮将具有的功能的参数,如下所示:
popup_instance.popup_with_action(i_want_to_call_this)
但是问题是参数被解析为字符串格式并且不可调用。
我不知道方法 button
的作用(我猜它会将作为参数传递的可调用对象绑定到给定按钮),但您应该考虑使用 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')