[note]构建常量

一般情况下,python之中没有常量。
但是,利用python的特性,可以构建“伪常量”,即一旦赋值便不能修改的变量。
涉及到赋值,在python中一个对象的赋值是由__setattr__完成的。
要想构建“伪常量”,必须对__setattr__这一函数进行修改。
比如在contant_class.py中:

class _const(object):
    """docstring for _const"""

    class ConstError(TypeError):          # 构建常量异常
        pass

    class ConstCaseError(ConstError):     # 构建常量的大小写异常
        pass


    def __setattr__(self, name, value):
        if name in self.__dict__:
            print("the value {name}can not be changed".format(name=name))               
            raise self.ConstError         # 已有属性不能在改变

        if not name.isupper():
            print( "the {name} should be capitalized.".format(name=name))
            raise self.ConstCaseError     # 属性的名字必须全为大写字母
        self.__dict__[name] = value

import sys
sys.modules[__name__] = _const()          # 利用python模块机制,引入本文件后自动加载_const实例

这样写代码时可以把所有常量保存在constan.py文件中。比如:

import const

const.OI = 1
const.PP = 'ookk'

如果在其他文件中需要引入常量,可以进行如下引用:

import constant

print(constant.const.OI)
print(constant.const.PP)
constant.const.OI = 2

当然“constant.const.OI = 2”会抛出异常,我们的目的就达到了。
运行结果如下:
1
ookk
the value OIcan not be changed
Traceback (most recent call last):
File “run.py”, line 5, in < module>
constant.const.OI = 2
File “C:\pyPro\notebook\const.py”, line 16, in __setattr__
raise self.ConstError
const.ConstError

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值