using concatenated strings as function call in python

I have aa function that takes as input 2 strings and a tuple of points. Based on the combination of those two strings, a specific function should be called on the tuple. I know that I could program some nested if statements, but I'm interested in the idea of calling an existing function from a string.

For example, I have a conversion function 'foo2bar(points)' which converts 'foo' points to 'bar' points. I have many other types of points and conversions between them. I now want to implement a 'type2type(points, oldtype, newtype)' which takes strings oldtype and newtype, and baed on those strings should call the appropriate conversion.

If I call type2type(points, 'foo','bar'), I want it to result in calling foo2bar(points).

Is there a way to generate function calls by concatenating strings like that? I want to say something like functionName = oldtype + '2' + newtype and then call 'functionName somehow.


Well, this isn't the safest way to do things, by you could use eval. Using the code you posted at the bottom, functionName = oldtype + '2' + newtype , you could just do:

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

You're almost there: after you've constructed functionName you just need to find the function. If your functions are all in a class, you could write something like this:

    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))

If they're module-level functions, you can look for them in 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/53236.html

上一篇: 如何统一发件人

下一篇: 在python中使用连接字符串作为函数调用