在python中使用连接字符串作为函数调用

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

例如,我有一个转换函数'foo2bar(points)',它将'foo'点转换为'bar'点。 我还有许多其他类型的点和转换。 我现在想实现一个'type2type(points,oldtype,newtype)',它需要字符串oldtype和newtype,并且对这些字符串进行引用应该调用适当的转换。

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

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


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

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

你几乎在那里:在你构造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))
链接地址: http://www.djcxy.com/p/53235.html

上一篇: using concatenated strings as function call in python

下一篇: asyncio how to pause coroutine until send is called