繁体   English   中英

在字典中存储函数[Python]

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM