Skip to main content
 首页 » 编程设计

Python:在创建字典时用作字典值时调用方法

2025年05月04日12zhujiabin

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

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 的构造期间被调用。 我在这里做错了什么?是因为我使用的装饰器吗?

请您参考如下方法:

他们被召唤是因为你召唤他们。不要那样做;将 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)