如何在 Python 中調用函數?九種方法任你挑選
1. 直接函數調用
這是最簡單、最直觀的方式:
- def test():
- print("This is a test")
- test()
2. 使用partial()函數
在 的內置庫中functools,有一個專用于生成偏函數的偏函數partial。
- def power(x, n):
- s = 1
- while n > 0:
- nn = n - 1
- ss = s * x
- return s
- from functools import partial
- power_2 = partial(power, n=2)
- power_2(3) # output: 9
- power_2(4) # output: 16
3. 使用 eval()
如果需要動態執行函數,可以使用 eval + string 來執行函數。
- # demo.py
- import 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)()
執行:
- $ python demo.py pre_task task post_task
- running pre_task
- running task
- running post_task
4. 使用 getattr()
如果把所有的函數都放在類中,并定義為靜態方法,就可以使用getattr()get和調用它們。
- import sys
- class Task:
- @staticmethod
- def pre_task():
- print("running pre_task")
- @staticmethod
- def task():
- print("running task")
- @staticmethod
- def post_task():
- print("running post_task")
- argvs = sys.argv[1:]
- task = Task()
- for action in argvs:
- func = getattr(task, action)
- func()
5. 使用 __dict__()
我們都知道對象有一個__dict__()魔法方法,它存儲任何對象的屬性和方法。
您可以調用類方法使用__dict__.get
- import sys
- class Task:
- @staticmethod
- def pre_task():
- print("running pre_task")
- func = Task.__dict__.get("pre_task")
- func.__func__()
- # Output
- $ python /tmp/demo.py
- running pre_task
6. 使用 global()
在 的內置庫中functools,有一個專用于生成偏函數的偏函數partial。
- import 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:
- globals().get(action)()
- # Output
- $ python /tmp/demo.py pre_task task post_task
- running pre_task
- running task
- running post_task
7. 從文本編譯和運行
您可以在字符串中定義您的函數,并使用該compile函數將其編譯為字節碼,然后用于exec執行它。
- pre_task = """
- print("running pre_task")
- """
- exec(compile(pre_task, '', 'exec'))
- # Or from a text file
- with open('source.txt') as f:
- source = f.read()
- exec(compile(source, 'source.txt', 'exec'))
8. 使用attrgetter()
在 的內置庫中operator,有一個獲取屬性的方法,稱為attrgetter,獲取函數后執行。
- from operator import attrgetter
- class People:
- def speak(self, dest):
- print("Hello, %s" %dest)
- p = People()
- caller = attrgetter("speak")
- caller(p)("Tony")
- # Output
- $ python /tmp/demo.py
- Hello, Tony
9. 使用methodcaller()
還有一個methodcaller方法在operator
- from operator import methodcaller
- class People:
- def speak(self, dest):
- print("Hello, %s" %dest)
- caller = methodcaller("speak", "Tony")
- p = People()
- caller(p)
- # Output
- $ python /tmp/demo.py
- Hello, Tony