I am trying to write a higher-order function that takes a varying amount of arguments. For instance something like this
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")
Is it possible to do this without changing the functions one_arg() or two_arg() ?
I've looked into using *argv but I don't think I understand it well enough or see a way to use that without changing those two functions
CodePudding user response:
you can just use * to define multiple 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")
Also for more details regarding functions and object oriented programming in python you can refer to this link
There are a lot more additional resources available online for you to learn
CodePudding user response:
Define higher
and call fnc
like this:
def higher(fnc, *args):
print(f"Calling function {fnc}")
fnc(*args)
Within the body of higher
, args
is a tuple of the positional arguments passed after fnc
. Calling fnc(*args)
spreads that tuple into individual positional arguments to fnc
.