实现python常量类

const 有什么好处? 最直接的好处是,防止被二次修改… 上次有个cdn刷新后端项目,直接使用config.py 做配置文件,因为有逻辑冲突串改了变量,导致服务没有限频限内存,导致服务crash… 当然,首先承认这是我编码的问题… 但如果变量一开始就是不可更改的常量,我是不是早就发现该问题了。 文章来自rui7157
实现:

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

from enum import Enum, unique

class Rui(Enum):
    a = 0
    b = 5
    c = 10


Rui.a.value
Rui.b.value

第二种方法,自己实现一个const类.

文件名: const.py

#coding:utf-8

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 const instance attribute (%s)"%name

        def __str__(self):
            return 'error msg: {}'.format(self.msg)

        def __repr__(self):
            return self.__str__()

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            raise self.ConstError(name)

        self.__dict__[name] = value

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

        raise self.ConstError(name)


sys.modules[__name__] = Const()

测试下错误:

import const

const.aa = 123
const.aa = 456

错误的输出:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    const.aa = 456
  File "/Users/NvRay/github/pyconsts/const.py", line 19, in __setattr__
    raise self.ConstError(name)
const.ConstError: error msg: Can't rebind const instance attribute (aa)

实现原理很简单,使用python类的魔法函数来定义setattr及delattr,出现重复就排除异常…
END.网站

文章来自rui7157

发布了9 篇原创文章 · 获赞 0 · 访问量 1341

猜你喜欢

转载自blog.csdn.net/rui7157/article/details/102952848