python实现常量类

const 有什么好处? 最直接的好处是,防止被二次修改导致整个程序崩掉!

第一种方法, 使用enum来定义变量,防止串改.

from enum import Enum, unique
# 若要不能定义相同的成员值,可以通过 unique 装饰
@unique 
class Const(Enum):
    a = 0
    b = 5
    c = 10
Const.a.value
Const.b.value

第二种方法,自己实现一个常量类(利用单例实现)

# coding:utf-8
# Filename:test.py
import sys
class _const:
    # 实现单例
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(_const, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance
    
    class ConstError(TypeError):
        def __init__(self, name):
            self.msg = "Can't rebind or unbind const instance attribute {0}".format(name)
        
        def __str__(self):
            return 'error msg: {}'.format(self.msg)
        
        def __repr__(self):
            return self.__str__()
    
    class ConstCaseError(ConstError):
        def __init__(self, name):
            self.msg = "const name {0} is not all uppercase".format(name)
        
        def __str__(self):
            return 'error msg: {}'.format(self.msg)
        
        def __repr__(self):
            return self.__str__()
    
    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError(name)
        if not name.isupper():
            raise self.ConstCaseError(name)
        self.__dict__[name] = value

    def __delattr__(self, name):
        if name in self.__dict__:
            raise self.ConstError(name)
        raise self.ConstError(name)

sys.modules[__name__] = _const() # 把Const类注册到sys.modules这个全局字典中(将系统加载的模块列表中的 test 替换为 _const() 实例)

在其他文件中定义常量:

import test
test.AA = 123 # 成功
test.bb = 111 # 报错,常量名需大写
test.AA = 111 # 报错,常量不能修改
del test.AA   # 报错,常量不能删除
posted @ 2022-08-30 10:23  阿木古冷  阅读(779)  评论(1编辑  收藏  举报