简单模块化
- import 最好在最顶端
- sys.path.append(“..”)表示把当前程序所在位置向上提了一级
- 在python3规范中,__init__.py并不是必须的。
文件结构:
.
├── utils
│ ├── util.py
│ └── class_util.py
├── src
│ └── sub_main.py
└── main.py
# utils/utils.py def get_sum(a, b): return a + b
# utils/class_utils.py class Encoder(object): def encode(self, s): return s[::-1] class Decoder(object): def decode(self, s): return ''.join(reverse(list(s)))
# main.py from utils.utils import get_sum print(get_sum(1, 2)) ########## 输出 ########## 3
# src/sub_main.py import sys sys.path.append("..") from utils.class_utils import * encoder = Encoder() decoder = Decoder() print(encoder.encode('abcde')) print(encoder.encode('edcba')) ########## 输出 ########## edcba abcde
项目模块化
以下Python代码用命令行运行main.py会出错,找不到proto.
├── proto
│ ├── mat.py
├── utils
│ └── mat_mul.py
└── src
└── main.py
# proto/mat.py class Matrix(object): def __init__(self, data): self.data = data self.n = len(data) self.m = len(data[0])
# utils/mat_mul.py from proto.mat import Matrix def mat_mul(matrix_1: Matrix, matrix_2: Matrix): assert matrix_1.m == matrix_2.n n, m, s = matrix_1.n, matrix_1.m, matrix_2.m result = [[0 for _ in range(n)] for _ in range(s)] for i in range(n): for j in range(s): for k in range(m): result[i][k] += matrix_1.data[i][j] * matrix_2.data[j][k] return Matrix(result)
# src/main.py from proto.mat import Matrix from utils.mat_mul import mat_mul a = Matrix([[1, 2], [3, 4]]) b = Matrix([[5, 6], [7, 8]]) print(mat_mul(a, b).data) ########## 输出 ########## [[19, 22], [43, 50]]
有两个方法解决:
1.在文件中强行修改sys.path[0]:
import sys sys.path[0] = '/home/ubuntu/workspace/your_projects'
2.在Python的虚拟环境中的activate文件,增加:(windows系统中无效)
export PYTHONPATH="/home/ubuntu/workspace/your_projects"
参考
极客时间《Python核心技术与实战》专栏