栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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


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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/638507.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号