【问题标题】:Python: methods are called when used as dict values while creation of the dictPython:在创建字典时用作字典值时调用方法
【发布时间】:2019-03-03 11:39:25
【问题描述】:

我想要一个带有方法的调度程序 dict{str:method}。我想遍历调度​​程序键并将值作为方法调用,但是当我运行 Python 脚本时,方法会在创建 dict 后立即执行:

from python.helper.my_client import Client

def deco_download(f):
    def f_download(*args, **kwargs):
        # some retry functionality here
        return json_data
    return f_download 

class Downloader:
    def __init__(self):
        self.attribute = 'some_value'

    @deco_download
    def download_persons(self, client, *args, **kwargs):
        return client.get_persons(*args, **kwargs)

    @deco_download
    def download_organizations(self, client, *args, **kwargs):
        return client.get_organizations(*args, **kwargs)

def run(self):
    dispatcher = {
        'person': self.download_persons(client),
        'organization': self.download_organizations(client)
    }

    for key in dispatcher:
        print("Downlading data for: {0}".format(key)
        dispatcher[key]

不幸的是,在我在 for 循环中调用它们之前初始化调度程序字典时直接执行这些方法。我希望它们在 for 循环中被调用,而不是在 dict 的构建过程中。 我在这里做错了什么?是因为我使用的装饰器吗?

【问题讨论】:

  • 请修复缩进。
  • @schwobaseggl - 我不明白,代码似乎完全缩进了我。你可以说得更详细点吗?编辑:好的,我找到了。
  • 例如return f_download 根本没有缩进,这对于 return 语句来说是不可能的

标签: python python-3.x dictionary methods


【解决方案1】:

他们被称为是因为你打电话给他们。不要那样做;将 callables 放入字典中。

def run(self):
    dispatcher = {
        'person': self.download_persons,
        'organization': self.download_organizations
    }

    for key in dispatcher:
        print("Downlading data for: {0}".format(key)
        dispatcher[key](client)

【讨论】:

    【解决方案2】:

    在创建dict的过程中干脆不要执行函数:

    def run(self):
        dispatcher = {
            'person': self.download_persons,
            'organization': self.download_organizations
        }
    
        for key in dispatcher:
            print("Downlading data for: {0}".format(key)
            dispatcher[key](client) # execute the function here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2019-08-07
      • 2012-02-02
      • 2021-10-25
      • 2023-03-15
      • 1970-01-01
      • 2020-04-04
      相关资源
      最近更新 更多