简体   繁体   English

在字典中存储函数[Python]

[英]Storing Functions in Dictionary [Python]

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). 我正在构建一个应用程序,我需要迭代一系列基本相同的步骤,节省了很少的代码(~15行)。 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. 步骤数将根据项目的配置方式而有所不同,因此为每个潜在实例创建单独的函数似乎有点愚蠢。

In JavaScript, I would do something like this: 在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]();

Is there a way to do something similar to this in python? 有没有办法在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? 还有什么更好的办法吗?

You can do this as follows: 你可以这样做:

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

This is one way only. 这只是一种方式。 There are many others. 还有很多其他的。 eg using lambdas, dict as you wanted, etc. 例如,如你所愿使用lambdas,dict等。

To use lambdas if your functions are one line only, you can do: 如果你的函数只有一行,要使用lambdas,你可以这样做:

func_list = [lambda: print("lambda1"), 
             lambda: print("lambda2"), 
             lambda: print("lambda1")]

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. 看起来似乎没有办法在Python中做到这一点,因为它被解雇为非Pythonic而故意制定了一个设计决策。 Oh well, it looks like I'm stuck defining the methods and then manually adding them to a list to iterate through. 哦,看起来我似乎无法定义方法,然后手动将它们添加到列表中以进行迭代。

Source: https://softwareengineering.stackexchange.com/a/99245 资料来源: 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.

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

I typically go about this like the following. 我通常会这样做,如下所示。 I like this approach, because it adds a minimum of typing overhead to the code, and if you write an additional method later on, nothing needs to be modified elsewhere in the file. 我喜欢这种方法,因为它为代码添加了最少的打字开销,如果稍后再写一个额外的方法,则无需在文件的其他地方修改任何内容。

def steptest0():
    code
def steptest1():
    code
def steptest2():
    code

...

tests = filter(lambda x: x.startswith('steptest'),
               dir())
for t in tests: eval(t + '()')

Every method is already put into a dictionary automatically in Python, and dir() lets us access that. 每个方法都已经在Python中自动放入字典中,而dir()允许我们访问它。

Disclaimer. 免责声明。 There are multiple alarm bells starting to go off in the head of the average pedestrian zealot at the sight of "eval" and some may even have seizures. 在看到“eval”的情况下,普通行人狂热者的头部开始出现多个警钟,有些甚至可能有癫痫发作。 Let them guard themselves from eval by using a reflection mechanism instead (which might make it less readable, but still worth it, as they can't be accused of using "eval"). 让他们通过使用反射机制来保护自己免受eval(这可能会使它不那么可读,但仍然值得,因为他们不能被指责使用“eval”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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