如何在 Python 中调用函数?九种方法任你挑选

时间:2022-11-03 17:43:23

如何在 Python 中调用函数?九种方法任你挑选

1. 直接函数调用

这是最简单、最直观的方式:

  1. def test():
  2. print("This is a test")
  3. test()

2. 使用partial()函数

在 的内置库中functools,有一个专用于生成偏函数的偏函数partial。

  1. def power(x, n):
  2. s = 1
  3. while n > 0:
  4. nn = n - 1
  5. ss = s * x
  6. return s
  7.  
  8.  
  9. from functools import partial
  10.  
  11. power_2 = partial(power, n=2)
  12. power_2(3) # output: 9
  13. power_2(4) # output: 16

3. 使用 eval()

如果需要动态执行函数,可以使用 eval + string 来执行函数。

  1. # demo.py
  2. import sys
  3.  
  4.  
  5. def pre_task():
  6. print("running pre_task")
  7.  
  8.  
  9. def task():
  10. print("running task")
  11.  
  12.  
  13. def post_task():
  14. print("running post_task")
  15.  
  16.  
  17. argvs = sys.argv[1:]
  18.  
  19.  
  20. for action in argvs:
  21. eval(action)()

执行:

  1. $ python demo.py pre_task task post_task
  2. running pre_task
  3. running task
  4. running post_task

4. 使用 getattr()

如果把所有的函数都放在类中,并定义为静态方法,就可以使用getattr()get和调用它们。

  1. import sys
  2.  
  3.  
  4. class Task:
  5. @staticmethod
  6. def pre_task():
  7. print("running pre_task")
  8.  
  9.  
  10. @staticmethod
  11. def task():
  12. print("running task")
  13.  
  14.  
  15. @staticmethod
  16. def post_task():
  17. print("running post_task")
  18.  
  19.  
  20. argvs = sys.argv[1:]
  21.  
  22.  
  23. task = Task()
  24.  
  25.  
  26. for action in argvs:
  27. func = getattr(task, action)
  28. func()

5. 使用 __dict__()

我们都知道对象有一个__dict__()魔法方法,它存储任何对象的属性和方法。

您可以调用类方法使用__dict__.get

  1. import sys
  2.  
  3.  
  4. class Task:
  5. @staticmethod
  6. def pre_task():
  7. print("running pre_task")
  8.  
  9.  
  10. func = Task.__dict__.get("pre_task")
  11. func.__func__()
  12. # Output
  13. $ python /tmp/demo.py
  14. running pre_task

6. 使用 global()

在 的内置库中functools,有一个专用于生成偏函数的偏函数partial。

  1. import sys
  2.  
  3.  
  4. def pre_task():
  5. print("running pre_task")
  6.  
  7.  
  8. def task():
  9. print("running task")
  10.  
  11.  
  12. def post_task():
  13. print("running post_task")
  14.  
  15.  
  16. argvs = sys.argv[1:]
  17.  
  18.  
  19. for action in argvs:
  20. globals().get(action)()
  21. # Output
  22. $ python /tmp/demo.py pre_task task post_task
  23. running pre_task
  24. running task
  25. running post_task

7. 从文本编译和运行

您可以在字符串中定义您的函数,并使用该compile函数将其编译为字节码,然后用于exec执行它。

  1. pre_task = """
  2. print("running pre_task")
  3. """
  4. exec(compile(pre_task, '', 'exec'))
  5. # Or from a text file
  6. with open('source.txt') as f:
  7. source = f.read()
  8. exec(compile(source, 'source.txt', 'exec'))

8. 使用attrgetter()

在 的内置库中operator,有一个获取属性的方法,称为attrgetter,获取函数后执行。

  1. from operator import attrgetter
  2.  
  3.  
  4. class People:
  5. def speak(self, dest):
  6. print("Hello, %s" %dest)
  7.  
  8.  
  9. p = People()
  10. caller = attrgetter("speak")
  11. caller(p)("Tony")
  12. # Output
  13. $ python /tmp/demo.py
  14. Hello, Tony

9. 使用methodcaller()

还有一个methodcaller方法在operator

  1. from operator import methodcaller
  2.  
  3.  
  4. class People:
  5. def speak(self, dest):
  6. print("Hello, %s" %dest)
  7.  
  8.  
  9. caller = methodcaller("speak", "Tony")
  10. p = People()
  11. caller(p)
  12. # Output
  13. $ python /tmp/demo.py
  14. Hello, Tony

原文地址:https://mp.weixin.qq.com/s?__biz=MzI3NDk3MDgxMA==&mid=2247486926&idx=1&sn=52a641a6f58d29532a91b16dbc711a7f&chksm=eb0aac1bdc7d250de8cc6154047926b20c04ad49bc0f12f9593952de4176fa79010c70f241f1&mpshare=1&s