将一长串常量导入到Python文件 [英] Importing a long list of constants to a Python file
问题描述
在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"
函数 init 在myExample中的
行13 self.someValueOne =
Constants.MY_CONSTANT_ONE + 1个副本
输出程序在0.06秒后以代码#1
退出。
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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!