Python对Const的理解与阐述

这篇博客介绍了Python中如何通过创建一个Const类来模拟常量行为,防止变量被意外修改。通过将Const实例赋值给sys.modules['const'],可以实现一个全局常量模块,用于集中管理项目的常量,如邮件协议常量。这种方式提供了代码的可读性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const’s interpretation

  • You guess

The python language itself does not provide const, but const is often encountered in actual development, and since the language itself does not have such expenditure, some tricks are needed to achieve this function。

Const

import sys
class Const(object):
    class ConstError(TypeException): pass
    def __setattr__(self, key, value):
        if self.__dict__.has_key(key):
            raise self.ConstError, "Changing const.%s" % key
        else:
            self.__dict__[key] = value
    def __getattr__(self, key):
        if self.__dict__.has_key(key):
            return self.key
        else:
            return None
sys.modules[__name__] = Const()

sys.modules
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.

个人理解:

sys.modules[name] =
Const()这条语句将系统已加载的模块列表中的const替换为了Const(),即一个Const实例

这样,整个工程需要使用的常量都应该定义在一个文件中
from project.utils import const
const.MAIL_PROTO_IMAP = ‘imap’
const.MAIL_PROTO_GMAIL = ‘gmail’
const.MAIL_PROTO_HOTMAIL = ‘hotmail’
const.MAIL_PROTO_EAS = ‘eas’
const.MAIL_PROTO_EWS = ‘ews’

from project.utils import const时,发生了sys.modules[name] = Const(),此时const模块已经加载进入内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值