Python dict to select 函数运行所有这些

1 python dictionary function python-3.x

因此,我尝试通过使用 dict 来选择要运行的函数来减少嵌套的 if。在测试中调用 execute 时,我通常使用 "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]()
Run Code Online (Sandbox Code Playgroud)

myp*_*ion 5

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

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