简体   繁体   中英

Python - passing a function as an argument to another function

I have two files;

  1. The first file, myProgram.py , is a python file with a number of functions
    one of the functions contained inside is myFunction this function would be called with

     import myProgram myProgram.thisFunction() myProgram.thatFunction() 
  2. The second file contains a menu system, with calls to the functions in myProgram.py

I'd like to call a particular function based on an argument passed to a function in file2

def file2_function(function):
    myProgram.function

file2_function(thisFunction(x,y,z))

which would essentially create myProgram.thisfunction(x,y,z) and execute it.

I guess I could do this using a bunch of if/elif statements, say:

def file2_function(function):
    if function == 1:
        myProgram.thisFunction
    elif function == 2: 
        myProgram.thatFunction

Though that could get messy as I'm already using a lot of if/elif/else statements for the menu system.

Is there a better way (or is the if/elif route the way to go?)

You can create a dictionary where key is the name of the function, and value is the function itself. Short example:

functions = { 'add' : lambda x,y : x + y, 'mult': lambda x,y : x * y, 'div' : lambda x,y : x / y, 'sub' : lambda x,y : x - y  }
functions['add'](1,2) # returns 3

The *args in the function file2_function means the arguments to be passed to the function in which it calls:

def func1(a):
    print a

def file2_function(function,*args):
    function(*args)

file2_function(func1,4)
#4

@aga gave you a good hint. When I'm writing cli applications I usually do smth like:

def func1():
    pass

def func2():
    pass

def func3():
    pass

def func_caller(name):
    func_dict = {
        'func1': func1,
        'func2': func2,
        'func3': func3
        }
    try:
        func_dict[name]()
    except KeyError:
        print "no such func"

Alternatively you have getattr . See following snippet:

>>> import sys
>>> getattr(sys,'exc_info')
<built-in function exc_info>
>>> getattr(sys,'exc_info')()
(None, None, None)

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