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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM