在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)