首页 > 解决方案 > Python dict to select 函数运行所有这些

问题描述

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

但由于某种原因,它会同时运行两次 BACKUP 选项。我究竟做错了什么?我正在使用 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]()

标签: pythonpython-3.xfunctiondictionary

解决方案


你没有将你的execute函数存储在你的options字典中。您正在存储调用该函数的结果。而且由于它是相同的函数,传入不同的参数,你实际上并不需要函数作为你的字典中的值。你需要参数。将最后四行更改为:

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

推荐阅读