当前位置: 首页 > news >正文

python解耦重构,提高程序维护性

一、重构思想

  1. 思路来源

java spring设计模式学习,强调低耦合的思想,通过解耦来提高程序的可维护性。

二、代码重构

  1. 解决方案
    通过单独配置文件来控制变量的改变。
    spring的话可以读取xml或者是springboot 读取application.properties 来获取变量值。
    python 使用以ini结尾配置文件。
  2. 方案优点
    让更改代码更方便,不需要查看所有的源码。
    集中在一个配置文件中,方便其他人员使用及维护。
  3. ini配置主要使用方法
    后面可以加注解
 # 

telephone2022 这个section 的部分, 每个文件可以有多个section

 [telephone2022]  

相等于 key =batch_number, value=3

batch_number = 3
  1. 具体实施
    first 建立一个config.ini 配置文件。
# batch_number 第几次做、send_date 做的日期
# date_change 做的月份 、month_new 数据给的最新月份
#  date_yzs 数据生成日期
[telephone2022]
batch_number = 3
send_date = 2024-07-03[2022]
date_change = 2024-05
month_new = 7
date_yzs = 20240702[Global]
date= 2024-07-03

second 安装解析库

pip install configparser

three python文件读取 config.ini 配置文件

import configparser
def read_config(section,key):"""读取配置文件:param section:  配置的section名:param key: 配置section名下变量:return: 配置section名下变量的值"""# 配置的路径file_path = r'config.ini'config = configparser.ConfigParser()config.read(file_path,encoding='utf-8')return config.get(section, key)# 使用方法
print(read_config('telephone2022', 'month_new'))

其他文件可以调用read_config 函数获取这个值

print(read_config('telephone2022', 'month_new'))

four 把read_config 封装起来,例如以下方案封装。

import os
# 获取当前文件的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 计算上上上级目录的路径
parent_parent_parent_dir = os.path.join(current_dir, '../../../')
# 将上上上级目录添加到Python的搜索路径
sys.path.append(parent_parent_parent_dir)
# 现在可以导入上上上级目录中的模块
from config.dataconfig import read_config
print(read_config('telephone2022', 'month_new'))

三、重构展望

  1. 深入设计模式
    欢迎一起沟通交流代码重构。
http://www.lryc.cn/news/390833.html

相关文章:

  • 深入解析 Laravel 事件系统:架构、实现与应用
  • 视频怎么制作gif动态图片?GIF制作方法分享
  • js 使用 lodash-es 检测某个值是否是函数
  • [go-zero] goctl 生成api和rpc
  • docker -run hello-world超时
  • 拓扑学习系列(8)黎曼度量曲面与高斯曲率
  • 汽车IVI中控开发入门及进阶(三十四):i.MX linux BSP
  • 【Python机器学习】算法链与管道——构建管道
  • Postman 高级用法学习
  • 从新手到高手:Scala函数式编程完全指南,Scala 访问修饰符(6)
  • IDEA 一键部署Docker
  • linux centos tomcat 不安全的HTTP请求方法
  • 深入Django(六)
  • PHP房产小程序微信小程序系统源码
  • vscode 历史便携版下载方法
  • 深入理解计算机系统 CSAPP 家庭作业8.19
  • JDBC学习(Java DataBase Connectivity)
  • 2024源代码加密软件评测丨保护企业源代码防泄密
  • 测试图片上传功能,使用postman提供的url
  • 使用dot来画流程图
  • 基于Java的微信记账小程序【附源码】
  • uniapp中 uni.previewImage用法
  • 第十三章 StringTable
  • Adobe Acrobat添加时间戳服务器
  • 数据库管理-第217期 Oracle的高可用-02(20240704)
  • 搭建基础库~
  • 深入了解Linux中的udhcpc:动态主机配置协议客户端
  • O2OA(翱途) 开发平台之HTTP端口规划
  • 以创新思维驱动下的盲盒小程序:重塑用户体验
  • 设计资料:520-基于ZU15EG 适配AWR2243的雷达验证底板 高速信号处理板 AWR2243毫米波板