sta*_*ech 1 python methods dictionary python-3.x
我希望有一个带有方法的调度程序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]
Run Code Online (Sandbox Code Playgroud)
不幸的是,在我在for循环中调用它们之前初始化调度程序dict时,这些方法是直接执行的.我希望它们可以在for循环中调用,而不是在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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |