![](/img/trans.png)
[英]What is the best way to define a (maybe hierarchical) set of constants in python?
[英]What's the best way to initialise and use constants across Python classes?
以下是我如何声明常量并在不同的 Python 类中使用它们:
# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3
# project/question.py
from constants import AWFUL, BAD, GOOD
class Question:
def __init__(self):
...
以上是存储和使用常量值的好方法吗? 我意识到一段时间后,常量文件会变得非常大,我可以明确地在任何给定文件中导入 10 多个这些常量。
为什么不直接使用
import constants
def use_my_constants():
print constants.GOOD, constants.BAD, constants.AWFUL
从 python 禅:
命名空间很好。 让我们做更多这些!
编辑:除了,当你引用时,你应该包括一个参考并检查它,因为正如其他人指出的那样,它应该是:
命名空间是一个很棒的想法——让我们做更多的事情!
这一次,我居然是从源头抄来的: PEP 20 -- Python的禅
如果常量绑定到特定的 class 并在该 class 中私下使用,则您还可以选择使它们特定于该 class:
class Foo(object):
GOOD = 0
BAD = 1
WTF = -1
def __init__(self...
离开你go。
你有几个选择:
从开销的角度来看,1 和 2 大致相同。 至于您关于导入特定常量的问题,使用以下约定之一要容易得多:
import constants; some_func(constants.AWFUL)
from constants import *; some_func(AWFUL)
尝试查看以下链接(一个链接包含来自活动 state 的收据,说明如何实现实常数):
我使用 function 作为不可变常量,如下所示:
def test_immutable_constant():
def GOOD():
return 1
good_value = GOOD()
good_value = 2
assert GOOD() == 1
assert good_value == 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.