I want to pass a method as an argument that will call such method from another python file as follows:
def abc():
return 'success.'
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?
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.
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.
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.
Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With