python - 我可以防止修改 Python 中的对象吗?

标签 python global-variables

我想以在程序初始化代码中只设置一次的方式控制全局变量(或全局范围变量),然后锁定它们。

我对全局变量使用 UPPER_CASE_VARIABLES,但我想有一个可靠的方法,无论如何都不要更改变量。

  • python 是否提供该(或类似)功能?
  • 您如何控制全局范围的变量?

最佳答案

ActiveState 有一个名为 Cᴏɴsᴛᴀɴᴛs ɪɴ Pʏᴛʜᴏɴ 的食谱由尊者 Alex Martelli用于创建一个 const 模块,其属性在创建后无法重新绑定(bind)。除了大写之外,这听起来像您要查找的内容 — 但可以通过检查属性名称是否全部大写来添加。

当然,这可以被确定的人规避,但这就是 Python 的方式 - 并且被大多数人认为是“好东西”。但是,为了让它变得更困难,我建议您不要费心添加所谓的显而易见的 __delattr__ 方法,因为人们随后可以删除名称,然后将它们重新添加回不同的值。

这就是我要说的:

放入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!")

输出:

const name 'Answer' is not all uppercase
const.ANSWER set to 42 raised no exception
Can't change const.ANSWER

关于python - 我可以防止修改 Python 中的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3711657/

相关文章:

c++ - 跟踪在 C++ 中调用递归函数的次数

c++ - 如何删除使用 SWIG 生成的 Python 包装器中的堆对象?

python - 使用Python填充缺失数据

python - 是否可以使用 SQLAlchemy 将 SQLite 数据库读入内存?

c++ - 静态常量类成员

javascript - 传递全局变量来导入 JS 模块

python - 如何在 matplotlib mplot3D 或类似文件中显示 3D 数组等值面的 3D 图?

python - 在 Django 上保存表单后重定向

c++ - C++ 中全局变量的替代品

javascript - 在函数中使用全局变量的副本