简体   繁体   中英

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

But what if... I want mainFunction0 to have some sort of argument (one or multiple arguments), that I want to reference with,

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

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:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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