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)

 

转载于:https://www.cnblogs.com/goingforward/p/10006066.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值