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

时间:2018-03-13 18:57:46

标签: python python-3.x function reverse

问题陈述:

我正在尝试从我的数据中读取行,并通过将我的列表传递给函数来输出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

但我似乎无法解决这个问题。

2 个答案:

答案 0 :(得分:2)

不要使用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

答案 1 :(得分:2)

以下是评论中已经提出的方法:

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的默认参数。

总之,重要的一点是,不需要传递函数的名称,以便然后查找该函数并调用它。只需将函数本身作为参数传递。