在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