簡體   English   中英

在 Python 中執行不同功能組合的最佳方式

[英]Best way to execute combination of different functions in Python

假設定義了n函數,每個函數代表一些動作,而函數代表這些動作的組合:

def all_actions():
    action1()
    action2()
    action3()
    ...
    actionN()

def combination_of_1_and_2():
    action1()
    action2()

def combination_of_1_and_3():
    action1()
    action3()

def combination_of_1_2_and_3():
    action1()
    action2()
    action3()

.....

如何在不為每個組合編寫單獨的 function 的情況下在 Python 中實現此功能?

更新

如果您將此問題視為基於意見的問題,則必須將有關最佳實踐的任何問題視為基於意見的問題,並且不允許這樣做。 但是定義說: Coding best practices are a set of informal rules that the software development community employ to help improve the quality of software. ,這意味着它們都是非正式的並且基於社區意見。

實現此目的的一種動態方法是將所有函數的引用存儲在列表(或字典)中,並根據索引調用函數。 例如::

my_action = [action0, action1, action2, .... , actionN]

my_action[1]()   # perform action1()
my_action[N]()   # perform actionN()

並定義單個 function 以根據索引執行操作:

def do_action(actions):
    for action in actions:
        my_action[action]()

使用do_action function,無需為所有操作組合定義自定義函數,您只需傳遞這些操作的索引即可。 例如:

do_action([1, 3, 5])

# Equivalent of:
#    action1()
#    action3()
#    action5()

對於執行所有操作,您可以簡單地傳遞range(N)

do_action(range(N))

如果將所有函數放入一個數組中,則可以簡單地根據數組索引調用函數。 因此,要進行組合,您可以像這樣使用 function:

def combination(fns):
    for i in fns:
        actions[i-1]()

例如:

def action1():
    print('action1')
    
def action2():
    print('action2')
    
def action3():
    print('action3')
    
actions = [action1, action2, action3]
    
def combination(fns):
    for i in fns:
        actions[i-1]()
        
combination([1, 3])

Output

action1
action3

然后你可以這樣寫all_actions

def all_actions():
    for i in range(len(actions)):
        actions[i]()

您也可以將一組操作傳遞給combination function。 例如:

def combination(fns):
    for fn in fns:
        fn()
        
combination([action1, action2])

Output:

action1
action2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM