选择功能的Python dict将全部运行 [英] Python dict to select function runs all of them

查看:71
本文介绍了选择功能的Python dict将全部运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试通过使用命令选择要运行的函数来减少嵌套if。在测试中调用execute时,我通常使用 execute( BACKUP, / home / src, / home / dest)来调用它

So I tried cutting down on nested if's by using a dict to select a function to run. When calling execute in a test I'm usually calling it with "execute("BACKUP","/home/src","/home/dest")"

但是由于某种原因,它两次都运行BACKUP选项。我究竟做错了什么?我正在使用Python3

But for some reason it runs both the BACKUP option twice. What am I doing wrong? I'm using Python3

    def execute(jobtype, src, dst):
        if jobtype == "FULL":
            _o_src = fs.Index(src)
            fs.MakeFolders(_o_src.GetFolders(), dst)
            fs.MakeFiles(src, dst, _o_src.GetFiles())
        if jobtype == "INCREMENTAL":
                print("DO INCREMENTAL BACKUP " + src + " TO " + dst)
    # Do the things
    options = {
                "BACKUP": execute(self.jobtype, self.src, self.dst),
                "RESTORE": execute(self.jobtype, self.dst, self.src),
              }
    options[jobtype]()


推荐答案

您没有存储您的执行中的执行函数。您正在存储调用该函数的结果。而且由于这两种方法都是相同的函数,并且传递了不同的参数,因此您实际上不需要将该函数用作dict中的值。您需要参数。将最后四行更改为:

You're not storing your execute function in your options dict. You're storing the result of calling that function. And since it's the same function either way with different parameters being passed in, you don't actually need the function to be the values in your dict. You need the parameters. Change your last four lines to:

options = {
          "BACKUP": [self.jobtype, self.src, self.dst],
          "RESTORE": [self.jobtype, self.dst, self.src],
          }
execute(*options[jobtype])

这篇关于选择功能的Python dict将全部运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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