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)
  • 相关阅读:
    【转】 springBoot(5)---单元测试,全局异常
    【转】 springBoot(4)---热部署,配置文件使用
    【转】 springBoot(3)---目录结构,文件上传
    【转】 springBoot(2)---快速创建项目,初解jackson
    【转】 springBoot(1)---springboot初步理解
    【转】 SpringBoot+MyBatis+MySQL读写分离
    简单请求 vs 非简单请求
    H5新增的API
    图片
    vue更新dom的diff算法
  • 原文地址:https://www.cnblogs.com/goingforward/p/10006066.html
Copyright © 2011-2022 走看看