Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does python have template equivalent method like C++?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading