Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to pass a method as an argument to call a method from another library

I want to pass a method as an argument that will call such method from another python file as follows:

file2.py

def abc():
    return 'success.'

main.py

import file2
def call_method(method_name):
    #Here the method_name passed will be a method to be called from file2.py
    return file2.method_name()

print(call_method(abc))

What I expect is to return success.

If calling a method within the same file (main.py), I notice it is workable. However, for case like above where it involves passing an argument to be called from another file, how can I do that?

like image 237
manwong0606 Avatar asked Mar 04 '18 03:03

manwong0606


People also ask

How do you pass a method as an argument in Python?

Methods are passed as arguments just like a variable. In this example, we define a class and its objects. We create an object to call the class methods. Now, to call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name.

How do you call a class method from another class method in Python?

Call method from another class in a different class in Python. we can call the method of another class by using their class name and function with dot operator. then we can call method_A from class B by following way: class A: method_A(self): {} class B: method_B(self): A.

Can you use a function as a parameter of another function Python?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions.

How can I use a function output as an input of another function in Python?

Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.


1 Answers

You can use getattr to get the function from the module using a string like:

import file2
def call_method(method_name):
    return getattr(file2, method_name)()

print(call_method('abc'))
like image 82
Stephen Rauch Avatar answered Oct 06 '22 01:10

Stephen Rauch