首页 > 解决方案 > Python调用函数作为来自另一个具有新值的函数的参数,Python

问题描述

我需要通过制作一个函数而不是几个我想要输出的函数来优化我的行数:

0 0
0 1
0 2
0 3
0 4

和尽可能少的功能。我需要通过我无权访问的函数 1 调用它。

我的代码如下所示:

# I have a direct access to this function and I want to call it by giving it val and other_val
def f0(val, other_val=None):
    print(val, other_val)

# I don't have a direct access to this function because it's in a library
def f1(function):
    function(0)


if __name__ == '__main__':
    # I need to call this specific function and pass other_val aswell but can't because f1 is in a library
    f1(f0)  # other_val = 0
    f1(f0)  # other_val = 1
    f1(f0)  # other_val = 2
    f1(f0)  # other_val = 3
    f1(f0)  # other_val = 4

标签: python

解决方案


我认为这样的事情会起作用:

other = 0
def f2(function, othr):
    global other
    other = othr
    return function

# I have a direct access to this function and we want to call it by giving it val and other_val
def f0(val):
    print(val, other)

# I don't have a direct access to this function because it's in a library
def f1(function):
    function(0)


if __name__ == '__main__':
    # I need to call this specific function and pass other_val aswell
    f1(f2(f0, othr=0))  # other_val = 0
    f1(f2(f0, othr=1))  # other_val = 1
    f1(f2(f0, othr=2))  # other_val = 2
    f1(f2(f0, othr=3))  # other_val = 3
    f1(f2(f0, othr=4))  # other_val = 4

推荐阅读