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)
  • 相关阅读:
    服务器基础知识
    web服务器与应用服务器
    QGraphics
    对话框Dialog
    信号和槽
    nginx 杂记
    go语言nsq源码解读八 http.go、http_server.go
    go语言nsq源码解读七 lookup_protocol_v1.go
    go语言nsq源码解读六 tcp.go、tcp_server.go
    go语言nsq源码解读五 nsqlookupd源码registration_db.go
  • 原文地址:https://www.cnblogs.com/goingforward/p/9883789.html
Copyright © 2011-2022 走看看