我试图写一个高阶函数,它包含不同数量的参数。例如,像这样的事情
def higher(fnc, args):
print(f"Calling function {fnc}")
fnc(argv)
def one_arg(only_arg):
print(f"Here is the only arg {only}")
def two_arg(first, second):
print(f"Here is the first {first} And here is the second {second}")
higher(one_arg, "Only one argument")
higher(two_arg, "Here's one arg", "and Another one")在不更改函数one_arg()或two_arg()的情况下,可以做到这一点吗?
我已经研究过使用*argv,但是我认为我还不够理解它,也没有找到一种不用改变这两个函数就可以使用它的方法
发布于 2022-11-18 00:01:27
您只需使用*来定义多个args。
def higher(fnc, *args):
print(f"Calling function {fnc}")
fnc(*args)
def one_arg(only_arg):
print(f"Here is the only arg {only_arg}")
def two_arg(first, second):
print(f"Here is the first {first} And here is the second {second}")
higher(one_arg, "Only one argument")
higher(two_arg, "Here's one arg", "and Another one")此外,有关python中的函数和面向对象编程的更多细节,请参阅此链接。
网上有更多的额外资源可供您学习。
发布于 2022-11-18 00:01:10
定义higher并按如下方式调用fnc:
def higher(fnc, *args):
print(f"Calling function {fnc}")
fnc(*args)在higher的主体中,args是在fnc之后传递的位置参数的元组。调用fnc(*args)将元组扩展为单个位置参数到fnc。
https://stackoverflow.com/questions/74483499
复制相似问题