Python的 - 传递一个函数作为参数传递给另一个函数 [英] Python - passing a function as an argument to another function

查看:265
本文介绍了Python的 - 传递一个函数作为参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件;


  1. 第一个文件, myProgram.py ,是多项功能Python文件结果
    里面包含的功能之一是 myFunction的
    这个功能将与被称为

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


  • 第二个文件包含一个菜单系统,通过调用函数在 myProgram.py

    我想基于传递给函数file2中的参数调用特定的功能

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

    这将基本上创建myProgram.thisfunction(X,Y,Z)和执行它。

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

    我想我能做到这一点使用了一堆的if / elif的语句,说:

    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
    

    虽然这是我已经使用了很多的菜单系统,如果/ ELIF / else语句可能会导致混乱。

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

    有没有更好的办法(或者是if / elif的路线走的方式?)

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

    推荐答案

    另外,您有 GETATTR 。请参见下面的代码片段:

    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)
    

    这篇关于Python的 - 传递一个函数作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆