将函数名作为变量连接到另一个函数

2024-05-19 07:05:48 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个关于人工智能的学校项目,我需要能够将一个函数名连接到另一个函数,例如:

def b_test(x):
    return x+1

def a_test(x):
    return x

variable = "b"
variable+= "_test"
a_test = variable

But this happenned

我猜Python希望使用名称“b”作为函数a\u test的新名称/别名,而不是使用b\u test作为新名称。你知道吗

那么,我怎样才能强迫python看b的意思而不是仅仅使用它呢?你知道吗

编辑:

我想做的是:

我的变量variable中有字符串b,当我在代码中使用a_test(x)时,我需要返回x+1(函数b_test的返回)。所以我将字符串“\u test”添加到变量中,使其成为“b\u test”。你知道吗

我可以通过编码来实现

a_test = b_test

但我不会只连接一个\u测试到b\u测试,它可能是c\u测试或d\u测试,这就是为什么我需要使用一个变量。你知道吗


Tags: 项目函数字符串代码test名称编辑return
2条回答

首先需要构造函数名(从变量中)并检索模块名,这样就可以在所需的变量中加载python函数对象。你知道吗

代码如下:

def b_test(x):
    return x + 1


def a_test(x):
    return x


def main():
    # Construct function name
    test_option = "b"  # "a"                                                                                                                                                                                                                                                   
    test_name = test_option + "_test"

    # Retrieve function module
    import os
    import importlib
    module_name = os.path.splitext(os.path.basename(__file__))[0]
    module = importlib.import_module(module_name)

    # Retrieve function
    test = getattr(module, test_name)

    # Debug information
    if __debug__:
        print ("Current file: " + str(__file__))
        print ("Module name: " + str(module_name))
        print ("Module: " + str(module))
        print ("Test function name: " + str(test_name))
        print ("Test function: " + str(test))

    # Execute function
    result = test(1)
    print ("Result: " + str(result))


if __name__ == '__main__':
    main()

一些重要注意事项:

  • test选项将只是一个包含要加载的测试函数的字符串。你知道吗
  • 不要“重命名”a\u test函数,只需使用test变量来指向要执行的正确函数
  • getattr函数对文件名和模块有点棘手,因此如果您修改此代码,可能需要修改函数模块的计算方式。你知道吗

你的例子实际上应该是可行的,但它并不能反映你的实际代码和屏幕截图中的错误。在您的屏幕截图中,您正试图从mlp\u functions模块获取ChosenFunction,该模块没有该属性,因此是AttributeError。要使用str名称从模块中获取属性,需要使用getattr,如:

mlp_functions.logistic_function = getattr(mlp_functions, ChosenFunction)

相关问题 更多 >

    热门问题