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

一、重构思想

  1. 思路来源

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

二、代码重构

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

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

bash 复制代码
 [telephone2022]  

相等于 key =batch_number, value=3

bash 复制代码
batch_number = 3
  1. 具体实施
    first 建立一个config.ini 配置文件。
bash 复制代码
# 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 安装解析库

bash 复制代码
pip install configparser

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

python 复制代码
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 函数获取这个值

python 复制代码
print(read_config('telephone2022', 'month_new'))

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

python 复制代码
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. 深入设计模式
    欢迎一起沟通交流代码重构。
相关推荐
大数据魔法师1 小时前
DuckDB高阶实战指南!多文件处理、窗口函数、性能调优、工程化落地
python·数据分析
李永奉1 小时前
C语言-嵌入式开发C语言常用预处理指令合集
c语言·开发语言
Patrick在香港2 小时前
Python Docker镜像从1.2GB到89MB:多阶段构建的完整优化实录
java·python·docker·信息可视化·容器·数据分析·ai编程
上海安当技术2 小时前
敏感数据怎么防拖库?信封加密(DEK+KEK 二层密钥)架构设计与 Java 实战
java·开发语言·python
我是唐青枫2 小时前
Java JCommander 实战详解:用注解解析命令行参数
java·开发语言
大鹏说大话2 小时前
C++ 内存布局详解:类、虚函数、虚表底层原理
java·开发语言
键盘会跳舞2 小时前
C++:容器适配器 queue 的源码级拆解
开发语言·c++·queue
QAQo7T3 小时前
Python组蓝桥杯备赛超详细知识点总结笔记_排序算法篇
笔记·python·算法·蓝桥杯·排序算法
醉颜凉3 小时前
蓝桥杯2025年第十六届省赛真题-最大数字 Python题解
python·职场和发展·蓝桥杯
Loge编程生活3 小时前
打卡信奥刷题(3449)用C++实现信奥题 P10429 [蓝桥杯 2024 省 B] 拔河
开发语言·数据结构·c++·算法·青少年编程