Skip to main content
 首页 » 编程设计

python之Python代码中常量、参数等放在什么位置进行研究

2025年05月04日8lyj

<分区>

背景:我目前正在实现一些环境过程的预测模型。如果您愿意,可以想象一个模型可以计算某些生态系统对不同温度的 react 。

这是我第一次在 Python 中做这样的事情,我对如何组织我的文件有点了解。我已经阅读了相关问题,但它们似乎大多是关于不同的用例和/或处理更深入的问题,而不是关于在哪里放置常量、参数等。

举个我现在拥有的例子:

常量.py:

# these should never be touched 
CONST1 = 1 
CONST2 = 2 
# etc 

参数.py:

# these can and should be changed by the user 
par1 = 1 
par2 = 2 
par3 = 3 
# etc 

模型.py:

# here are the model's functions 
import constants as c 
 
def fun1(par1, par2): 
    res1 = c.CONST1 * par1 + par2 
    return res1 
 
def fun2(par2, par3): 
    res2 = c.CONST2 * par2 + par3 
    return res2 
# etc 

主要.py:

# this file is used to run the model 
import model as m 
import parameters as p 
 
res1 = m.fun1(p.par1, p.par2) 
res2 = m.fun2(p.par2, p.par3) 
# plot results etc 

像这样将常量、参数和函数保存在单独的文件中是个好主意,还是至少这些常量应该是 model.py 中的全局变量,因为我无论如何都不会碰它们?单文件解决方案(一个 .py 中的常量、参数、模型和主函数)的“极端情况”是否被认为是糟糕的风格?几乎所有函数都使用的变量(例如时间,或我在 model.py 中导入的常量)怎么样:我应该明确地将它们传递给每个函数,还是可以/应该使它们成为全局变量?

TL;DR:如果有关于如何组织这样的项目的任何最佳实践,请帮助新手程序员。