将一长串常量导入Python文件

SK9*_*SK9 72 python constants python-import

在Python中,是否存在C预处理器语句的类似物,例如?:

#define MY_CONSTANT 50

另外,我有一个很大的常量列表,我想导入几个类.是否有类似的方法将常量声明为.py文件中的上述长序列语句并将其导入另一个.py文件?

编辑.

该文件Constants.py为:

#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""

MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

编辑.

从编译器,

NameError:"未定义全局名称'MY_CONSTANT_ONE'"

第13行的myExample中的函数init self.someValueOne = Constants.MY_CONSTANT_ONE + 1复制输出程序在0.06秒后退出代码#1.

Tho*_*s K 104

Python未经过预处理.你可以创建一个文件myconstants.py:

MY_CONSTANT = 50
Run Code Online (Sandbox Code Playgroud)

导入它们只会起作用:

import myconstants
print myconstants.MY_CONSTANT * 2
Run Code Online (Sandbox Code Playgroud)


小智 16

Python没有预处理器,也没有常量,因为它们无法更改 - 你总是可以改变(几乎可以模拟常量对象属性,但为了恒定而这样做很少)完成并且不被认为有用)一切.在定义一个常量时,我​​们定义一个带有下划线的大写的名称,并将其称为一天 - "我们都在同意这里的成年人",没有理智的人会改变常数.当然,除非他有充分的理由并且确切地知道他在做什么,在这种情况下你不能(并且不应该)阻止他.

但是,您当然可以使用值定义模块级名称并在另一个模块中使用它.这不是特定于常量或任何东西,在模块系统上阅读.

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT
Run Code Online (Sandbox Code Playgroud)


ton*_*ony 9

当然,你可以这样做:

# a.py
MY_CONSTANT = ...

# b.py
from a import *
print MY_CONSTANT
Run Code Online (Sandbox Code Playgroud)

  • 通常不建议使用import*,但是在代码库中广泛使用的C风格的清单常量是使用它并不是疯狂的地方之一.在ALL_CAPS中命名它们或使用一些减少与其他符号冲突的可能性的前缀约定消除了对成语的主要反对意见,如果确实发生了冲突,您可以始终回退到传统的import +显式名称样式(导入a; a .MY_CONSTNAT),与C不同. (3认同)
  • [`import*`是魔鬼.](http://docs.python.org/howto/doanddont.html#from-module-import) (2认同)

NPE*_*NPE 7

当然,您可以将常量放入单独的模块中.例如:

const.py:

A = 12
B = 'abc'
C = 1.2
Run Code Online (Sandbox Code Playgroud)

main.py:

import const

print const.A, const.B, const.C
Run Code Online (Sandbox Code Playgroud)

需要注意的是如上述声明A,B并且C是变量,即可以在运行时改变.


Fre*_*ihl 5

作为使用几个答案中描述的导入方法的替代方法,请查看configparser模块。

ConfigParser 类实现了一种基本的配置文件解析器语言,该语言提供的结构类似于您在 Microsoft Windows INI 文件中可以找到的结构。您可以使用它来编写可由最终用户轻松定制的 Python 程序。


Art*_*nka 5

尝试查看使用“设置”模块创建常量?并且可以防止在Python中修改对象吗?

另一个有用的链接:http : //code.activestate.com/recipes/65207-constants-in-python/告诉我们以下选项:

from copy import deepcopy

class const(object):

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
            return deepcopy(self.__dict__[name])
        self.__dict__[name] = value

    def __getattr__(self, name, value):
        if self.__dict__.has_key(name):
            return deepcopy(self.__dict__[name])

    def __delattr__(self, item):
        if self.__dict__.has_key(item):
            print 'NOOOOO' # throw exception if needed

CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'
Run Code Online (Sandbox Code Playgroud)

因此,您可以创建一个像这样的类,然后从contants.py模块中将其导入。这样可以确保不会更改,删除值。