[英]Storing Functions in Dictionary [Python]
我正在構建一個應用程序,我需要迭代一系列基本相同的步驟,節省了很少的代碼(~15行)。 步驟數將根據項目的配置方式而有所不同,因此為每個潛在實例創建單獨的函數似乎有點愚蠢。
在JavaScript中,我會做這樣的事情:
var switches = [true, true, false, true];
var holder = {
0: function() { /* do step0 */ }
1: function() { /* do step1 */ }
2: function() { /* do step2 */ }
3: function() { /* do step3 */ }
// ...etc...
}
for (var i = 0; i < switches.length; i++)
if (switches[i])
holder[i]();
有沒有辦法在python中做類似的事情? 我唯一能想到的是這樣的事情:
switches = [True, True, False, True]
class Holder(object):
@staticmethod
def do_0():
# do step0
@staticmethod
def do_1():
# do step 1
# ...etc...
def __repr__(self):
return [self.do_0, self.do_1, ...]
for action in Holder:
action()
如果我有大量的步驟,這似乎非常低效。 還有什么更好的辦法嗎?
你可以這樣做:
# define your functions
def fun1():
print("fun1")
def fun2():
print("fun2")
def fun3():
print("fun3")
switches = [True, False, True];
# put them in a list (list makes more sense than dict based on your example)
func_list = [fun1, fun2, fun3]
# iterate over switches and corresponding functions, and execute
# functions when s is True
for s,f in zip(switches, func_list):
if s: f()
這只是一種方式。 還有很多其他的。 例如,如你所願使用lambdas,dict等。
如果你的函數只有一行,要使用lambdas,你可以這樣做:
func_list = [lambda: print("lambda1"),
lambda: print("lambda2"),
lambda: print("lambda1")]
看起來似乎沒有辦法在Python中做到這一點,因為它被解雇為非Pythonic而故意制定了一個設計決策。 哦,看起來我似乎無法定義方法,然后手動將它們添加到列表中以進行迭代。
資料來源: https : //softwareengineering.stackexchange.com/a/99245
- Your functions don't need to be enveloped in a utility class.
- I don not see how the two blocks of code differ in efficiency.
- You can use enumerate and lambdas to simplify your code.
簡化代碼
d = {0: lambda: 'Performing Step 0',
1: lambda: 'Performing Step 1',
2: lambda: 'Performing Step 2',
3: lambda: 'Performing Step 3',
4: lambda: 'Performing Step 4'}
for index, switch in enumerate([1, 0, 1, 1, 0]):
if switch == 1: d[index]()
我通常會這樣做,如下所示。 我喜歡這種方法,因為它為代碼添加了最少的打字開銷,如果稍后再寫一個額外的方法,則無需在文件的其他地方修改任何內容。
def steptest0():
code
def steptest1():
code
def steptest2():
code
...
tests = filter(lambda x: x.startswith('steptest'),
dir())
for t in tests: eval(t + '()')
每個方法都已經在Python中自動放入字典中,而dir()
允許我們訪問它。
免責聲明。 在看到“eval”的情況下,普通行人狂熱者的頭部開始出現多個警鍾,有些甚至可能有癲癇發作。 讓他們通過使用反射機制來保護自己免受eval(這可能會使它不那么可讀,但仍然值得,因為他們不能被指責使用“eval”)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.