【问题标题】:Converting List of Strings into List of Callable Functions in Python [duplicate]在Python中将字符串列表转换为可调用函数列表[重复]
【发布时间】:2021-12-01 19:33:12
【问题描述】:

我已经从电子邮件中抓取了一些字符串到一个列表中。这些字符串对应于我希望稍后能够调用的函数的名称。我不能以它们当前的形式调用它们,所以有没有办法将字符串列表转换为我可以调用的函数列表?

例如:

a = ['SU', 'BT', 'PL']
str = 'sdf sghf sdfgdf SU agffg BL asu'
matches = [x for x in a if x in str]
print(matches)

返回:

 ['SU', 'BL']

但是给定格式,我不能从这个列表中调用函数 SU 和 BL。

【问题讨论】:

  • 你可以制作一个函数字典,其中字符串是键,函数是值。然后运行your_dict[key]()。你试过了吗?
  • Python 中的函数名本身就是一个变量。所以你真正想做的是从它的名字中检索一个变量引用。方法是运行 import sys 然后 getattr(sys.modules[__name__], FUNCTION_NAME) 。它将从全局范围内为您检索变量。例如,如果您已经定义了一个名为myfunc 的函数,那么您可以使用f = getattr(sys.modules[__name__], 'myfunc')。然后你可以从你的变量中调用函数:f()。它将调用函数myfunc()
  • 一个建议 - 不要使用 str 作为变量。谢谢
  • @Mahrkeenerh 非常正确。 >>> str(4) ; '4' ; >>> str = 'blalsd' ; >>> str(4) ; Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable
  • 巧合的是,这个例子说明了函数名称与 Python 中的其他变量的区别

标签: python


【解决方案1】:

用这个例子:

def my_func1():
    print("ONE")

def my_func2():
    print("TWO")

你可以试试eval,但这不是一个好习惯:(explanation)

eval("my_func1")()

或者您可以将此函数分配给等效字符串(在字典中),然后运行:

my_func_dict = {
    "my_func1": my_func1, 
    "my_func2": my_func2
}

my_func_dict["my_func1"]()

这两个示例都将打印ONE

或者更接近你的例子:

a = [my_func1, my_func2]

matches = [x for x in a if x.__name__ in str]

# matches now has two funcions inside, so you can run either:
matches[0]()
matches[1]()

【讨论】:

  • "你不能直接做:run("my_func")"这是假的,你可以做eval("my_func")()或类似的
  • 这在我身上,不知道这一点。我会编辑答案。
  • 您可以使用__name__ 属性。将可调用对象放入列表并将matches = [x for x in a if x in str] 更改为matches = [x for x in a if x.__name__ in str]
  • 使用eval 可能是不安全和危险的,具体取决于字符串的来源。如果输入来自用户表单,则有人可以输入(lambda: print('I do something evil!')),可以使用eval("(lambda: print('I do something evil!'))")() 执行。您应该避免使用eval的其他原因:stackoverflow.com/a/1832957/42659
猜你喜欢
  • 1970-01-01
  • 2016-08-10
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2017-10-21
  • 1970-01-01
  • 2020-10-30
相关资源
最近更新 更多