Importing a long list of constants to a Python file(将一长串常量导入 Python 文件)
问题描述
在 Python 中,是否有类似的 C
预处理器语句,例如?:
In Python, is there an analogue of the C
preprocessor statement such as?:
#define MY_CONSTANT 50
另外,我有一大串常量我想导入到几个类中.有没有类似的方法在 .py
文件中将常量声明为像上面这样的一长串语句并将其导入另一个 .py
文件?
Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a .py
file and importing it to another .py
file?
编辑.
文件 Constants.py
内容如下:
#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""
MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51
而 myExample.py
内容为:
#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""
import sys
import os
import Constants
class myExample:
def __init__(self):
self.someValueOne = Constants.MY_CONSTANT_ONE + 1
self.someValueTwo = Constants.MY_CONSTANT_TWO + 1
if __name__ == '__main__':
x = MyClass()
编辑.
来自编译器,
NameError: "全局名称'MY_CONSTANT_ONE' 未定义"
NameError: "global name 'MY_CONSTANT_ONE' is not defined"
function init in myExample at line13 self.someValueOne =常量.MY_CONSTANT_ONE + 1 份输出程序以代码 #1 退出0.06 秒后.
function init in myExample at line 13 self.someValueOne = Constants.MY_CONSTANT_ONE + 1 copy output Program exited with code #1 after 0.06 seconds.
推荐答案
Python 没有经过预处理.你可以只创建一个文件 myconstants.py
:
Python isn't preprocessed. You can just create a file myconstants.py
:
MY_CONSTANT = 50
导入它们就可以了:
import myconstants
print myconstants.MY_CONSTANT * 2
这篇关于将一长串常量导入 Python 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将一长串常量导入 Python 文件


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01