如何在 Python 中調(diào)用函數(shù)?九種方法任你挑選
1. 直接函數(shù)調(diào)用
這是最簡(jiǎn)單、最直觀的方式:
- def test():
- print("This is a test")
- test()
2. 使用partial()函數(shù)
在 的內(nèi)置庫(kù)中functools,有一個(gè)專用于生成偏函數(shù)的偏函數(shù)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()
如果需要?jiǎng)討B(tài)執(zhí)行函數(shù),可以使用 eval + string 來(lái)執(zhí)行函數(shù)。
- # 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)()
執(zhí)行:
- $ python demo.py pre_task task post_task
- running pre_task
- running task
- running post_task
4. 使用 getattr()
如果把所有的函數(shù)都放在類中,并定義為靜態(tài)方法,就可以使用getattr()get和調(diào)用它們。
- 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__()
我們都知道對(duì)象有一個(gè)__dict__()魔法方法,它存儲(chǔ)任何對(duì)象的屬性和方法。
您可以調(diào)用類方法使用__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()
在 的內(nèi)置庫(kù)中functools,有一個(gè)專用于生成偏函數(shù)的偏函數(shù)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. 從文本編譯和運(yùn)行
您可以在字符串中定義您的函數(shù),并使用該compile函數(shù)將其編譯為字節(jié)碼,然后用于exec執(zhí)行它。
- 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()
在 的內(nèi)置庫(kù)中operator,有一個(gè)獲取屬性的方法,稱為attrgetter,獲取函數(shù)后執(zhí)行。
- 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()
還有一個(gè)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