将其名称用作字符串时如何调用函数?

How to call a function when using its name as string?

问题陈述:

我试图从我的数据中读取行,并通过将我的列表传递给函数来输出 forwardreverse 方向。为了解决我想做的事情,我必须通过管道传输 function-name as string。我正在下面进行模拟测试,以简单的方式复制我原来的问题。

my_str = 'abcdef\nijklmn\nstuv\n'
my_str = my_str.rstrip('\n').split('\n')

for lines in my_str:
    print(lines)
    line_list = list(lines)

    # I want to read both forward and reverse orientation using a function "(def orient_my_str():"
    # the reason to pass this into another function is because I have lots of data crunching to do in each orientation (not shown here).
    # but, below process typically resolves what I am trying to achieve

    line_rev = orient_my_str(line_list, orientation='reversed')
    line_fwd = orient_my_str(line_list, orientation='')

    print('list in reverse orientation :', line_rev)
    print('list in forward orientation :', line_fwd)
    print()


# I am only want to make one function not two, because if I make two functions ..
# .. I will have to copy a large amount of code below the for-loop.
# there should be a way to fix this problem (calling function using string name when required and not).
def orient_my_str(line, orientation):
    my_output = ''
    for item in eval(orientation)(line):
        my_output += item

    print(my_output)
    return my_output

# But, this only works for reverse orientation. I know the issue is with passing "eval('')(line)" but was hoping it would work.

我尝试使用这些链接中的想法修复我的代码,

Use a string to call function in Python

Calling a function of a module by using its name (a string)

python function call with variable

但我似乎无法解决。

不要使用 eval,保持方法简单。您不需要复制 for:

下面的任何内容
def orient_my_str(line, reverse = False): 
    # add any needed preprocessing here, store result as new list
    # and use it in the following line instead of the variable line
    data = reversed(line) if reverse else line 

    my_output = ''
    for item in data: # operate on line or reversed line as needed
        my_output += item

    print(my_output)
    return my_output

line_list= ["1","2","3","4"]
line_rev = orient_my_str(line_list, reverse = True)
line_fwd = orient_my_str(line_list)

print(line_rev)
print(line_fwd)

输出:

4321
1234
4321
1234

这是评论中已经建议的方法:

def orient_my_str(line, preprocessor):
    my_output = ''
    for item in preprocessor(line):
        my_output += item

    print(my_output)
    return my_output

正如我提到的,您可以将函数作为参数传递。要调用它,您可以这样做:

line_rev = orient_my_str(line_list, preprocessor=reversed)
line_fwd = orient_my_str(line_list, preprocessor=lambda x: x)

如果您不喜欢显式传递 lambda 函数,您也可以为 preprocessor 使用默认参数。

总而言之,重要的一点是无需传递函数名称即可查找并调用该函数。只需将函数本身作为参数传递即可。