返回 首页

Implement a Java-like enumeration in Python


Consider to use the Enum class if your program consists of a fixed set of constants, like seasons of the year, operations calculator, user status, user genders and etc.

Java Enums

public enum ErrorCode {

    SUCCESS(0, ""),
    DUPLICATE_NAME(1, "商户名称重复"),
    EMPTY_LOGO(2, "商户 logo 为空"),
    EMPTY_BUSINESS_LICENSE(3, "商户营业执照为空"),
    ERROR_PHONE(4, "商户联系电话错误"),
    EMPTY_ADDRESS(5, "商户地址为空"),
    MERCHANTS_NOT_EXIST(6, "商户不存在");

    /** 错误码 */
    private Integer code;

    /** 错误描述 */
    private String desc;

    ErrorCode(Integer code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public Integer getCode() {
        return this.code;
    }

    public String getDesc() {
        return this.desc;
    }
}

Python Enums

class CardTypeEnum(Enum):
    ID_CARD = (1, '身份证')
    TRAVEL_FOR_HK_MR = (2, '港澳居民来往内地通行证')
    TRAVEL_FOR_TW = (3, '台湾居民来往大陆通行证')
    PASSPORT = (4, '护照')

    def __init__(self, code, text):
        self.code = code
        self.text = text


评论(0)

登录