【问题标题】:using concatenated strings as function call in python在python中使用连接字符串作为函数调用
【发布时间】:2018-01-26 19:42:22
【问题描述】:

我有一个函数,输入 2 个字符串和一个点元组。基于这两个字符串的组合,应该在元组上调用一个特定的函数。我知道我可以编写一些嵌套的 if 语句,但我对从字符串调用现有函数的想法很感兴趣。

例如,我有一个转换函数“foo2bar(points)”,它将“foo”点转换为“bar”点。我有许多其他类型的点和它们之间的转换。我现在想实现一个'type2type(points,oldtype,newtype)',它接受字符串oldtype和newtype,并且基于这些字符串应该调用适当的转换。

如果我调用 type2type(points, 'foo','bar'),我希望它调用 foo2bar(points)。

有没有办法通过像这样连接字符串来生成函数调用?我想说functionName = oldtype + '2' + newtype 之类的话,然后以某种方式调用'functionName。

【问题讨论】:

    标签: string python-3.x function


    【解决方案1】:

    嗯,这不是最安全的做事方式,你可以使用 eval。使用您在底部发布的代码functionName = oldtype + '2' + newtype,您可以这样做:

    functionName = oldtype + '2' + newtype
    args = [] #whatever arguments you want in the function
    eval(functionName+"(**args)")
    

    【讨论】:

      【解决方案2】:

      你就快到了:在你构造了functionName 之后,你只需要找到函数。如果你的函数都在一个类中,你可以这样写:

          def type2type(self, points, x, y):
              name = '{}2{}'.format(x, y)
              if hasattr(self, name):
                  return getattr(self, name)(points)
              else:
                  raise ValueError("No function named {}".format(name))
      

      如果是模块级函数,可以在globals中查找:

      def type2type(points, x, y):
          name = '{}2{}'.format(x, y)
          if name in globals():
              return globals()[name](points)
          else:
              raise ValueError("No function named {}".format(name))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 2018-12-23
        • 2011-05-07
        • 1970-01-01
        • 2021-11-17
        相关资源
        最近更新 更多