【问题标题】:Python dict to select function runs all of themPython dict to select 函数运行所有这些
【发布时间】:2018-10-21 06:49:42
【问题描述】:

所以我尝试通过使用 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]()

【问题讨论】:

  • ...因为您要调用它两次...
  • 好吧,对于初学者来说,不要调用函数...

标签: python python-3.x function dictionary


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多