zoukankan      html  css  js  c++  java
  • Python自定义状态码枚举类

    在Java里很容易做到自定义有状态码和状态说明的枚举类例如:

    public enum MyStatus {
      NOT_FOUND(404, "Required resource is not found");
    
      private final int code;
      private final String msg;
    
      private MyStatus (int code, String msg) {
        this.code= code;
        this.msg = msg;
      }
    
      public int getCode() {
        return this.code;
      }
    
      public String getMsg() {
        return this.msg;
      }
    
       public static String getMsgByCode(int code){
            for(MyStatus status: MyStatus.values()){
                if(status.getCode() == code){
                    return status.message;
                }
            }
            return null;
        }
    
    }

    但是在Python里没找到类似的可以这样做的方法,于是就利用了字典,不知道对不对,所以贴出来供参考和改进:

    # -*- coding: utf-8 -*
    """状态码枚举类
    
    author: Jill
    
    usage:
        结构为:错误枚举名-错误码code-错误说明message
        # 打印状态码信息
        code = Status.OK.get_code()
        print("code:", code)
        # 打印状态码说明信息
        msg = Status.OK.get_msg()
        print("msg:", msg)
    """
    from enum import Enum, unique
    
    
    @unique
    class Status(Enum):
        OK = {"200": "成功"}
        SUCCESS = {"000001": "成功"}
        FAIL = {"000000": "失败"}
        PARAM_IS_NULL = {"000002": "请求参数为空"}
        PARAM_ILLEGAL = {"000003": "请求参数非法"}
        JSON_PARSE_FAIL = {"000004": "JSON转换失败"}
        REPEATED_COMMIT = {"000005": "重复提交"}
        SQL_ERROR = {"000006": "数据库异常"}
        NOT_FOUND = {"000007": "无记录"}
        NETWORK_ERROR = {"000015": "网络异常"}
        UNKNOWN_ERROR = {"000099": "未知异常"}
    
        def get_code(self):
            """
            根据枚举名称取状态码code
            :return: 状态码code
            """
            return list(self.value.keys())[0]
    
        def get_msg(self):
            """
            根据枚举名称取状态说明message
            :return: 状态说明message
            """
            return list(self.value.values())[0]
    
    
    if __name__ == '__main__':
        # 打印状态码信息
        code = Status.OK.get_code()
        print("code:", code)
        # 打印状态码说明信息
        msg = Status.OK.get_msg()
        print("msg:", msg)
    
        print()
    
        # 遍历枚举
        for status in Status:
            print(status.name, ":", status.value)
  • 相关阅读:
    Android开源日志框架xlog
    [CrackMe]160个CrackMe之18
    SEH异常
    全局句柄表
    用户层异常的派发与处理
    用户层异常的处理
    内核层异常的收集与处理
    两种异常(CPU异常、用户模拟异常)的收集
    无处不在的页异常
    AppBoxFuture(四). 随需而变-Online Schema Change
  • 原文地址:https://www.cnblogs.com/goingforward/p/10006066.html
Copyright © 2011-2022 走看看