Member-only story
Python — Different Ways to Call Function
Directly Function Call
This is the simplest and most intuitive way:
def test():
print("This is a test")test()
Use partial() Function
In the built-in library of functools
, there is a partial method dedicated to generating partial functions.
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
from functools import partial
power_2 = partial(power, n=2)
power_2(3) # output: 9
power_2(4) # output: 16
Use eval()
If you need to execute the function dynamically, you can use eval + string to execute the function.
# demo.pyimport sys
def pre_task():
print("running pre_task")
def task():
print("running task")
def post_task():
print("running post_task")
argvs = sys.argv[1:]
for action in argvs:
eval(action)()
To execute:
$ python demo.py pre_task task post_task
running pre_task
running task
running post_task
Use getattr()
If you put all the functions in the class and define them as static methods, you can use getattr()
to…