【问题标题】:Call functions from string concatenations in for loop [Python]从 for 循环中的字符串连接调用函数 [Python]
【发布时间】:2014-08-25 02:53:22
【问题描述】:

我有几行将函数的结果添加到列表中。我试图把它变成一个循环,而不是连续的赋值行和追加。

到目前为止,我有我想要的代码,我只是在努力将实际的字符串转换为对函数的调用。我已经阅读了袖珍 python 指南和其他各种 python 书籍,但无法找到解决方案。

    categories = ['Hours', 'Travel', 'Site', 'Date']
    indexloc == 0
    for i in categories:  
        func = 'v'+categories[indexloc]+' = Get'+categories[indexloc]
        indexloc += 1

我得到的结果是我只是不确定如何将它们转换为函数调用:

>>> 
vHours = GetHours
vTravel = GetTravel
vSite = GetSite
vDate = GetDate
>>>

(只是为了澄清 Get 部分是函数调用)

我读过 Calling a function of a module from a string with the function's name in Python 但我没有看到它是否/如何适用于我的情况

Python 2.7 razcrasp@gmail.com 谢谢

【问题讨论】:

  • 您要调用的函数在哪里/如何定义?
  • 它们是之前在代码中定义的。它们都可以正常工作并且不需要参数。函数是结果部分中的 4。 GetHours、GetTravel、GetSite 和 GetDate。我需要将它们从字符串转换为函数调用

标签: python function python-2.7 for-loop call


【解决方案1】:

要调用一个函数,你需要对它有一些引用。既然知道函数名,就可以从局部变量中获取:

for category in categories:
    function = locals()['Get' + category]

    print 'v{} = {}'.format(category, function())

更好的方法是将类别名称映射到函数:

category_mapping = {
    'hours': GetHours,  # CamelCase is usually for classes, not functions
    'travel': GetTravel,
    ...
}

for category, function in category_mapping.items():
    print 'v{} = {}'.format(category.capitalize(), function())

【讨论】:

  • 哦,真正的菜鸟搬到那里,看来我需要复习我的 dicts/mapping 非常感谢
猜你喜欢
  • 2017-01-30
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多