在字典中存储函数[Python] [英] Storing Functions in Dictionary [Python]

查看:305
本文介绍了在字典中存储函数[Python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个应用程序,在该应用程序中,我需要遍历一系列步骤,这些步骤在很大程度上完成相同的工作,并节省少量的代码(约15行).步骤的数量将取决于项目的配置方式,因此,为每个潜在实例创建单独的功能对我来说似乎很愚蠢.

I'm currently building an application where I need to iterate over a series of steps that do largely the same thing, save a very small amount of code (~15 lines). The number of steps will vary depending on how the project is configured, so it seems kind of silly for me to create a separate function for each potential instance.

在JavaScript中,我会这样做:

In JavaScript, I would do something like this:

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中做类似的事情?我唯一能想到的就是这样:

Is there a way to do something similar to this in python? The only thing I can think of is something like this:

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()

如果我有很多步骤,这似乎效率很低.有没有更好的方法可以解决这个问题?

This just seems terribly inefficient if I have any significant number of steps. Is there any better way to go about this?

推荐答案

在Python中似乎没有办法做到这一点,这是有意做出的设计决策,因为它被认为是非Python风格的.哦,好了,好像我一直在定义方法,然后手动将它们添加到列表中以进行迭代.

It looks like there isn't a way to do this in Python, a design decision made intentionally since it was dismissed as un-Pythonic. Oh well, it looks like I'm stuck defining the methods and then manually adding them to a list to iterate through.

来源: https://softwareengineering.stackexchange.com/a/99245

这篇关于在字典中存储函数[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆