简体   繁体   English

字典功能:可以为“第2层”功能分配参数吗?

[英]Dictionary Functions: Can you assign an argument to a “Tier 2” function?

Thanks in advance for time spent on this enquiry. 预先感谢您花费在此查询上的时间。 I am curious to know if the following is possible. 我很想知道以下情况是否可能。 For the below code, is there syntax that will allow you to define an argument for a function (referenced by a dictionary) that is outside of the functions' "tier"? 对于下面的代码,是否有语法可以让您为函数“层”之外的函数(由字典引用)定义参数?

For this example: I have a main function, mainFunction(key) . 对于此示例:我有一个主要函数mainFunction(key) I can call either mainFunction0 or 1 with the last line mainFunction(mainReferences[0] ) IE changing the key to either a 0 or 1 concatenates the reference for the function name to be called. 我可以在最后一行mainFunction(mainReferences[0] )IE上调用mainFunction0或1,将键更改为0或1可以将要调用的函数名称的引用连接起来。

But what if... I want mainFunction0 to have some sort of argument (one or multiple arguments), that I want to reference with, 但是,如果...我希望mainFunction0具有某种我想引用的参数(一个或多个参数),

mainFunction(mainReferences[0])

I have tried the following, but none seem to work. 我已经尝试了以下方法,但是似乎都没有用。

mainFunction(mainReferences[0])(1)

mainFunction(mainReferences[0], 1)

Where the additional "1" in either case is the input for "testArg0" within function mainFunction0(testArg0) . 无论哪种情况,附加的“ 1”是函数mainFunction0(testArg0) “ testArg0”的输入。

Can this be done? 能做到吗? If so, is it also possible to enter multiple "outside of tier" arguments? 如果是这样,是否还可以输入多个“层外”参数?

Cheers! 干杯!

def mainFunction(key):

    def mainFunction0(testArg0):
        if testArg0 == 1:
            print("main function 1")
        else:
            pass

    def mainFunction1():
        print("main function 1")

    locals()['mainFunction' + key]() 

mainReferences  = ["0", "1"]

mainFunction(mainReferences[0])

You can either make mainFunction accept variable arguments: 您可以使mainFunction接受变量参数:

def mainFunction(key, *args, **kwargs):

    def mainFunction0(testArg0):
        if testArg0 == 1:
            print("main function 1")
        else:
            pass

    def mainFunction1():
        print("main function 1")

    locals()['mainFunction' + key](*args, **kwargs)

mainReferences  = ["0", "1"]

mainFunction(mainReferences[0], 1)

or make mainFunction return a function object and let the caller make the actual call: 或使mainFunction返回一个函数对象,然后让调用者进行实际的调用:

def mainFunction(key):

    def mainFunction0(testArg0):
        if testArg0 == 1:
            print("main function 1")
        else:
            pass

    def mainFunction1():
        print("main function 1")

    return locals()['mainFunction' + key]

mainReferences  = ["0", "1"]

mainFunction(mainReferences[0])(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM