我正在构建一个包含各种类和功能的解决方案,所有这些类和功能都需要访问一些全局使用者才能正常工作。由于python中没有const
,您认为设置一种全局使用者的最佳做法是什么。
global const g = 9.8
所以我正在寻找上面的一种
编辑:怎么样:
class Const():
@staticmethod
def gravity():
return 9.8
print 'gravity: ', Const.gravity()
答案 0 :(得分:12)
您无法在Python中定义常量。如果你发现某种黑客行为,你就会混淆每个人。
要做那种事情,通常你应该只有一个模块 - globals.py
,例如你导入到你需要它的地方
答案 1 :(得分:7)
一般惯例是用大写和下划线定义变量而不是改变它。像,
GRAVITY = 9.8
但是,可以使用namedtuple
import collections
Const = collections.namedtuple('Const', 'gravity pi')
const = Const(9.8, 3.14)
print(const.gravity) # => 9.8
# try to change, it gives error
const.gravity = 9.0 # => AttributeError: can't set attribute
对于namedtuple
,请参阅文档here