我在python中编写一个包含许多常量变量的程序。我想创建一个文件,它将保存所有这些变量,如C中包含许多#define的.h文件。我尝试使用configparser然而我发现使用它并不容易和有趣。
你知道更好的方法吗?
Python不允许像C或C ++这样的常量声明。
通常在Python中,常量是大写的(PEP 8标准),这有助于程序员知道它是常量。
防爆。 MY_CONSTANT = "Whatever"
另一种有效的方法,我不会使用但听说过,使用的方法是:
def MY_CONSTANT():
return "Whatever"
现在理论上,调用MY_CONSTANT()
就像一个常量。
编辑
就像评论所说,有人可以通过致电改变价值
MY_CONSTANT = lambda: 'Something else'
但不要忘记同一个人可以在第一个例子中调用MY_CONSTANT = "Something else"
并更改初始值。在这两种情况下都不太可能,但可能。
Python中没有常量,它们在C或Java中的存在方式。你可以通过功能来模仿它们:
def FOO():
return "foo"
您可以将函数调用包装在属性中,从而使其看起来像一个变量:
class Const:
@property
def FOO(self):
return "foo"
CONST = Const() # You need an instance
if something == CONST.FOO:
...
通过一些元元素,可以使用简洁的语法获得不可设置的属性:
def const(cls):
# Replace a class's attributes with properties,
# and itself with an instance of its doppelganger.
is_special = lambda name: (name.startswith("__") and name.endswith("__"))
class_contents = {n: getattr(cls, n) for n in vars(cls) if not is_special(n)}
def unbind(value): # Get the value out of the lexical closure.
return lambda self: value
propertified_contents = {name: property(unbind(value))
for (name, value) in class_contents.items()}
receptor = type(cls.__name__, (object,), propertified_contents)
return receptor() # Replace with an instance, so properties work.
@const
class Paths(object):
home = "/home"
null = "/dev/null"
现在您可以访问Paths.home
作为正常值,但无法分配给它。你可以定义几个用@const
修饰的类,因为你可能会使用几个.h
文件。
你可以使用这样的东西:
文件结构:
myapp/
__init__.py
settings.py
main.py
settings.朋友
CONST_A = 'A'
CONST_B = 'B'
__init__.朋友
from . import settings as global_settings
class Settings:
def __init__(self):
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
def __setattr__(self, attr, value):
if not getattr(self, attr, None):
super().__setattr__(attr, value)
else:
raise TypeError("'constant' does not support item assignment")
settings = Settings()
卖弄.朋友
import settings
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # raises TypeError error
print(settings.CONST_A) # prints A
settings.CONST_C = 'C' # also able to add new constants
print(settings.CONST_C) # prints C
在Settings类中覆盖__setattr__使所有属性都是只读的。唯一的要求是使用大写字母写出settings.py中的所有常量。但请注意,如果直接导入变量,它将不起作用:
from settings import CONST_A
print(settings.CONST_A) # prints A
settings.CONST_A = 'C' # sets C
print(settings.CONST_A) # prints C
Python未经过预处理。您只需创建一个constant.py文件即可
#!/usr/bin/env python
# encoding: utf-8
"""
constant.py
"""
MY_CONSTANT = 50
如果需要常量值,请导入constant.py文件,如下例所示。
#!/usr/bin/env python
# encoding: utf-8
"""
example.py
"""
import constant
print constant.MY_CONSTANT * 2
这样您就可以在项目中使用常量。
如果常量绑定到特定类并在该类中私有使用,使它们特定于该类,您也可以选择:
class Foo(object):
GOOD = 0
BAD = 1
def __init__(self...
如果要定义和使用整个模块,请将它们放在模块的顶部
PIE = 3.47
class Foo(object):
def __init__(self...
只需定义一个constants.py文件并编写所有常量。 Python中没有其他魔术技巧。使用大写作为一般惯例。