我可以防止在Python中修改对象吗?

我可以防止在Python中修改对象吗?,第1张

我可以防止在Python中修改对象吗?

Activestate有一个由古老的Alex
Martelli
撰写的题为“ Constants in
Python
”的食谱


用于创建具有创建后无法反d的属性的模块。听起来像您在寻找什么,除了大写字母-
但这可以通过检查属性名称是否全部大写来添加

const

当然,这可以由有决心的人规避,但这就是Python的方式—并被大多数人视为“好事”。但是,要使其变得更困难一点,我建议您不要去添加所谓的显而易见的

__delattr__
方法,因为人们可以随后删除名称,然后将其重新添加回不同的值。

这就是我要采取的措施:

# Put in const.py...# from http://pre.activestate.com/recipes/65207-constants-in-pythonclass _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 uppercaseconst.ANSWER set to 42 raised no exceptionCan't change const.ANSWER


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5644316.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存