Odoo 14中如何用字典替换Python代码中的多分支if判断
用字典替换多分支if实现部门报表生成
核心思路是把每个部门的报表生成逻辑封装成独立函数,通过字典建立「部门名称-处理函数」的映射,遍历部门时直接调用对应函数,彻底替代冗余的多分支if判断。
步骤1:定义各部门的处理函数
把每个部门的代码块封装成函数,传入所需的上下文参数(比如reconciliation_act、sheet、row等),函数完成报表写入后返回更新后的行号:
def handle_new_mb(reconciliation_act, sheet, row, col_format, date, col_format_number, date_period, empty_string, sales_new_mb, total_new_mb, date_with_customer_ref): new_mb_department_no_discount = [] # 按实际需求初始化列表 new_mb_department_no_discount.insert(1, reconciliation_act.partner_id.commercial_company_name) new_mb_department_no_discount.insert(2, reconciliation_act.currency_id.display_name) new_mb_department_no_discount.insert(7, sales_new_mb) new_mb_department_no_discount.insert(8, 'New MB') if reconciliation_act.reconciliation_act_date == reconciliation_act.period_to: new_mb_department_no_discount.insert(11, empty_string) new_mb_department_no_discount.insert(12, 'начисление выручки') else: sheet.write(row, 11, reconciliation_act.period_to, date_period) new_mb_department_no_discount.insert(13, 'корректировка выручки прошлых периодов') for col_num, data in enumerate(new_mb_department_no_discount): sheet.write(row, col_num, data, col_format) sheet.write(row, 0, reconciliation_act.reconciliation_act_date, date) sheet.write(row, 4, total_new_mb, col_format_number) sheet.write(row, 5, date_with_customer_ref, date) return row + 1 def handle_cpa(reconciliation_act, sheet, row, **kwargs): # 编写CPA部门的报表生成逻辑 return row + 1 def handle_alfasearch(reconciliation_act, sheet, row, **kwargs): # 编写Alfasearch部门的报表生成逻辑 return row + 1 def handle_inapp(reconciliation_act, sheet, row, **kwargs): # 编写inApp部门的报表生成逻辑 return row + 1
步骤2:构建部门-函数映射字典
将部门名称和对应的处理函数绑定:
department_dict = { 'CPA': handle_cpa, 'New MB': handle_new_mb, 'Alfasearch': handle_alfasearch, 'inApp': handle_inapp }
步骤3:修改循环逻辑
遍历部门时,从字典中取出对应函数并执行,同时更新行号:
# 打包通用参数,避免重复传递 common_params = { 'reconciliation_act': reconciliation_act, 'sheet': sheet, 'col_format': col_format, 'date': date, 'col_format_number': col_format_number, 'date_period': date_period, 'empty_string': empty_string, 'sales_new_mb': sales_new_mb, 'total_new_mb': total_new_mb, 'date_with_customer_ref': date_with_customer_ref } for department in reconciliation_act.reconciliation_act_line_ids.mapped("department_id.name"): handler = department_dict.get(department) if handler: row = handler(row=row, **common_params) else: # 可选:处理未知部门的逻辑 print(f"未配置部门{department}的报表生成规则")
注意事项
- 函数参数可根据实际场景调整,比如用
**kwargs接收通用参数,减少代码冗余 - 若多个部门存在重复逻辑,可提取为公共函数,在部门处理函数中调用
- 建议给每个处理函数添加注释,方便后续维护
内容的提问来源于stack exchange,提问作者user14213623
相关产品推荐
相关产品推荐

