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 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
推荐阅读
- python - 在 Python 中迭代包含字符串的大列表的最快方法是什么?
- javascript - 在渲染 UI 之前,如何从 async/await 函数中获取数据?
- laravel - Laravel:如何设置消耗品购买?
- python - fedora 的 python-boto3 和 python2-boto3 rpms 有什么区别?
- java - 获取kafka分区中的最后一条记录偏移量
- c# - 如何用十六进制值初始化 int?
- git - 不想将 staging 分支上的所有功能都带入 master
- python - 即使在定义 form_valid 之后,Django 中的 IntegrityError
- excel - 搜索的参数数量错误
- c# - 如何使用 C# 在 XML 文档中添加新元素