Python将函数作为参数从另一个具有新值Python的函数调用

Python将函数作为参数从另一个具有新值Python的函数调用,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 d

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

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

我想这样做会奏效:

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

我建议只使用单一功能:

# I have a direct access to this function and I want to call it by giving it val and other_val

other = 0
def f0(val):
    global other
    print(val, other)
    other += 1

# 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

您可以通过使用高阶函数来避免使用全局函数

def f0(other_val=None):
    def wrapped_f0(val):
        print(val, other_val)
    return wrapped_f0

def f1(function):
    function(0)


if __name__ == '__main__':
    f1(f0(0))
    f1(f0(1))
    f1(f0(2))
    f1(f0(3))
    f1(f0(4))

尝试使用全局变量。从f0定义中排除其他值,在函数外部创建
last=0
,然后在函数开头使用
global
关键字(如
global last
)从f0访问并修改它。若要包装现有函数,可能需要使用()。