I have a function that can apply to multiple situation.
For example, I have a function f that contains another function h, which can apply different function depend on the situation.
def f(n):
return n.cost + h(n)
and the h function will be determine before runtime.
I understand that I could just use f(n, h) to pass in different function, but that would mess up the parameter list, which I need it to stay only one parameter.
Therefore, I’m wondering if there is a way to achieve something like this in Python:
def f<h>(n):
return n.cost + h(n)
as in C++:
template<int (*H)>
int f(Node n)
{
return n.cost + H(n);
}
Thank you!
>Solution :
You can use a decorator function
def f_decorator(h):
def f(n):
return n.cost + h(n)
return f
def h(n):
return n**2
f = f_decorator(h)
print(f(2))