zoukankan      html  css  js  c++  java
  • Python常量工具类

    1.定义常量类constant.py

    # -*- coding: utf-8 -*
    """常量工具类
    
    author: Jill
    
    usage:
        from constant import _Const
        const = _Const()
        const.PI = 3.14
    """
    
    
    class _Const:
        class ConstError(TypeError):
            pass
    
        class ConstCaseError(ConstError):
            pass
    
        def __setattr__(self, name, value):
            if name in self.__dict__:
                raise self.ConstError("Can't change const(%s) value" % name)
            if not name.isupper():
                raise self.ConstCaseError("Const name %s is not all uppercase" % name)
    
            self.__dict__[name] = value
    
        def __getitem__(self, key):
            if key in self.__dict__:
                return self.__dict__[key]
            else:
                raise self.ConstError("Can't return const %s, No Existing Key!" % key)
    
        def __delattr__(self, name):
            if name in self.__dict__:
                raise self.ConstError("Can't unbind const(%s)" % name)
            raise NameError(name)

    2.将常量放在一个模块中common_constant.py

    # -*- coding: utf-8 -*
    """常用常量定义
    
    author: Jill
    
    usage:
        from common_constant import const
        print(const.ROOT_PATH)
    """
    from common.constant import _Const
    
    
    const = _Const()
    
    const.PI = 3.14
    
    if __name__ == "__main__":
        print(const.PI)
        print(const['PI'])

    3.在其他模块里使用test.py

    from common_constant import const
        
    
    print(const.ROOT_PATH)
  • 相关阅读:
    进程与线程(二) java进程的内存模型
    进程学习(一) 进程的地址空间
    在一个数组中除两个数字只出现1次外,其它数字都出现了2次
    倒水问题
    leecode 树是否是平衡树 java
    Max Sum
    Encoding
    海阔天空-
    Binomial Showdown
    Square
  • 原文地址:https://www.cnblogs.com/goingforward/p/9883789.html
Copyright © 2011-2022 走看看