我想控制全局变量(或全局范围的变量),使其在程序初始化代码中仅设置一次,然后锁定它们。
我使用 UPPER_CASE_VARIABLES 作为全局变量,但我想有一个确定的方法来不更改变量。
- python 是否提供该(或类似)功能?
- 如何控制全局范围的变量?
ActiveState 有一个名为Cᴏɴsᴛᴀɴᴛs ɪɴ Pʏᴛʜᴏɴ http://code.activestate.com/recipes/65207-constants-in-python由可敬的人亚历克斯·马泰利 http://en.wikipedia.org/wiki/Alex_Martelli用于创建一个const
具有创建后无法反弹属性的模块。这听起来像是您正在寻找的内容,除了大写之外 - 但可以通过检查属性名称是否全部大写来添加。
当然,有决心的人可以规避这一点,但这就是 Python 的方式,并且被大多数人认为是一件“好事”。然而,为了让它变得更加困难,我建议你不要费心添加所谓的显而易见的东西__delattr__
方法,因为人们可以删除名称,然后将它们添加回反弹到不同的值。
这就是我正在考虑的:
Put in const.py
:
# from http://code.activestate.com/recipes/65207-constants-in-python
class _const:
class ConstError(TypeError): pass # Base exception class.
class ConstCaseError(ConstError): pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError("Can't change const.%s" % name)
if not name.isupper():
raise self.ConstCaseError('const name %r is not all uppercase' % name)
self.__dict__[name] = value
# Replace module entry in sys.modules[__name__] with instance of _const
# (and create additional reference to it to prevent its deletion -- see
# https://stackoverflow.com/questions/5365562/why-is-the-value-of-name-changing-after-assignment-to-sys-modules-name)
import sys
_ref, sys.modules[__name__] = sys.modules[__name__], _const()
if __name__ == '__main__':
import __main__ as const # Test this module...
try:
const.Answer = 42 # Not OK to create mixed-case attribute name.
except const.ConstCaseError as exc:
print(exc)
else: # Test failed - no ConstCaseError exception generated.
raise RuntimeError("Mixed-case const names should't be allowed!")
try:
const.ANSWER = 42 # Should be OK, all uppercase.
except Exception as exc:
raise RuntimeError("Defining a valid const attribute should be allowed!")
else: # Test succeeded - no exception generated.
print('const.ANSWER set to %d raised no exception' % const.ANSWER)
try:
const.ANSWER = 17 # Not OK, attempt to change defined constant.
except const.ConstError as exc:
print(exc)
else: # Test failed - no ConstError exception generated.
raise RuntimeError("Shouldn't be able to change const attribute!")
Output:
const name 'Answer' is not all uppercase
const.ANSWER set to 42 raised no exception
Can't change const.ANSWER
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)