我试图找到一种方法来加载 JSON 对象,然后将键映射到 Python 函数的关键字参数。
这是现在的单个案例。
def load_new_category(self, filename):
basepath = os.path.dirname(__file__)
filepath = os.path.abspath(os.path.join(basepath, "..", "JSON", filename))
with open(filepath) as sample:
self.create_new_category(is_active=case['is_active'],
description=case['description'], page_title=case['page_title'],
meta_keywords=case['meta_keywords'], meta_description=case['meta_description'],
navigation_menu=case['navigation_menu'],
parent_filter_setting=case['parent_filter_setting'],
show_filter=case['show_filter'], sort_filter=case['sort_filter'])
这种模式出现在许多函数中,我正在寻找一种方法来推广到任何 JSON 文件和函数。也许是装饰师?
请您参考如下方法:
只需在此处使用 **kwargs 语法,因为您所有的关键字参数都一对一地映射到您的 JSON 对象键:
self.create_new_category(**case)
