gen*_*gen 8 python variables const declaration global-variables
我正在构建一个包含各种类和函数的解决方案,所有这些类和函数都需要访问一些全局使用者才能正常工作.由于const在python中没有,你会考虑设置一种全局意图的最佳实践.
global const g = 9.8
Run Code Online (Sandbox Code Playgroud)
所以我正在寻找上述一种
编辑:怎么样:
class Const():
@staticmethod
def gravity():
return 9.8
print 'gravity: ', Const.gravity()
Run Code Online (Sandbox Code Playgroud)
?
Joh*_*ooy 12
您无法在Python中定义常量.如果你发现某种黑客行为,你会混淆每个人.
要做那种事情,通常你应该只有一个模块 - globals.py例如你导入到你需要的任何地方
一般惯例是用资本和下划线定义变量而不是改变变量.喜欢,
GRAVITY = 9.8
Run Code Online (Sandbox Code Playgroud)
但是,可以使用Python在Python中创建常量 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
Run Code Online (Sandbox Code Playgroud)
对于namedtuple,请参阅此处的文档