我有一個帶有以下代碼的列舉類:
# enums.py
class AuthCode(Enum):
ALREADY_AUTHENTICATED = 1
MISSING_EMAIL = 2
MISSING_PASSWORD = 3
MISSING_REGISTRATION_TOKEN_CODE = 4
INVALID_EMAIL = 5
REDEEMED_EMAIL = 6
INVALID_PASSWORD = 7
INVALID_REGISTRATION_TOKEN_CODE = 8
REDEEMED_REGISTRATION_TOKEN_CODE = 9
INVALID_CREDENTIALS = 10
SIGNIN_SUCCESSFUL = 11
REGISTRATION_SUCCESSFUL = 12
class AuthCodeMessage(Enum):
AuthCode.ALREADY_AUTHENTICATED = "User was already logged in"
AuthCode.MISSING_EMAIL = "Email was not specified"
AuthCode.MISSING_PASSWORD = "Password was not specified"
AuthCode.MISSING_REGISTRATION_TOKEN_CODE = "Registration token code was not specified"
AuthCode.INVALID_EMAIL = "Email is invalid"
AuthCode.REDEEMED_EMAIL = "An account with this email has been created already"
AuthCode.INVALID_PASSWORD = "Password does not meet minimum password requirements"
AuthCode.INVALID_REGISTRATION_TOKEN_CODE = "Registration token code is invalid"
AuthCode.REDEEMED_REGISTRATION_TOKEN_CODE = "Registration token code has been redeemed already"
AuthCode.INVALID_CREDENTIALS = "Account with these credentials does not exist"
AuthCode.SIGNIN_SUCCESSFUL = "User has been signed in successfully"
AuthCode.REGISTRATION_SUCCESSFUL = "User account has been created successfully"
是否可以按照定義的方式定義第二個列舉 (AuthCodeMessage)(即,使用另一個列舉作為鍵)。如何檢索列舉值?
編輯 1:我想使用類似于以下的方法從我的代碼中呼叫我的列舉:
from enums import AuthCode, AuthCodeMessage
def authResponse(authCode):
AuthCode.ALREADY_AUTHENTICATED
return jsonify({
"code": authCode,
"message": AuthCodeMessage.authCode
})
authResponse(AuthCode.ALREADY_AUTHENTICATED)
uj5u.com熱心網友回復:
您真正想要的是將AuthCodes映射到字串。在 Python 中執行此操作的常用方法是使用字典,如下所示:
AUTHCODE_MESSAGES = {
AuthCode.ALREADY_AUTHENTICATED: "User was already logged in",
# copy the rest of the code/message pairs here
# make sure to replace the = with :
# and add a , on the end of every line
}
然后你可以像這樣使用它:
# FIXME: enums is not a very clear name for what it does.
from enums import AuthCode, AUTHCODE_MESSAGES
def authResponse(authCode):
return jsonify({
"code": authCode,
"message": AUTHCODE_MESSAGES[authCode]
})
uj5u.com熱心網友回復:
而不是使用兩個列舉,只需使用一個。使用檔案中的AutoNumber 配方(第二個),您的代碼將如下所示:
class AuthCode(AutoNumber):
ALREADY_AUTHENTICATED = "User was already logged in"
MISSING_EMAIL = "Email was not specified"
MISSING_PASSWORD = "Password was not specified"
...
def __init__(self, description):
self.description = description
后來:
def authResponse(authCode):
return jsonify({
"code": authCode.value,
"message": authCode.description,
})
——
披露:我是Python stdlibEnum、enum34backport和Advanced Enumeration ( aenum) 庫的作者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/402996.html
標籤:
下一篇:如何在包中匯入同級檔案?
