为什么字典在课堂上不起作用?

时间:2018-12-25 17:12:23

标签: python python-3.x

为什么我不能使用在类中定义的字典?我正在尝试在定义它的下面一行中使用字典。

这不起作用:

class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser):
    GENDER_UNKNOWN = 0
    GENDER_FEMALE = 1
    GENDER_MALE = 2
    GENDER_OTHER = 3
    GENDER_MAX_VALUE_PLUS_ONE = 4

    GENDER_FEMALE_STRING = 'female'
    GENDER_MALE_STRING = 'male'
    GENDER_OTHER_STRING = 'other'

    GENDER_CHOICES = (
        (GENDER_FEMALE, _("Female")),
        (GENDER_MALE, _("Male")),
        (GENDER_OTHER, _("Other")),
    )
    GENDER_VALID_VALUES = [choice[0] for choice in GENDER_CHOICES]
    GENDERS_DICT = {GENDER_FEMALE: GENDER_FEMALE_STRING, GENDER_MALE: GENDER_MALE_STRING, GENDER_OTHER: GENDER_OTHER_STRING}
    print(GENDERS_DICT) # for debugging.
    ALL_GENDERS = [GENDERS_DICT[gender] for gender in GENDER_VALID_VALUES]

(它打印{1: 'female', 2: 'male', 3: 'other'}并抛出异常:NameError: name 'GENDERS_DICT' is not defined

但这可行:

class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser):
    GENDER_UNKNOWN = 0
    GENDER_FEMALE = 1
    GENDER_MALE = 2
    GENDER_OTHER = 3
    GENDER_MAX_VALUE_PLUS_ONE = 4

    GENDER_FEMALE_STRING = 'female'
    GENDER_MALE_STRING = 'male'
    GENDER_OTHER_STRING = 'other'

    GENDER_CHOICES = (
        (GENDER_FEMALE, _("Female")),
        (GENDER_MALE, _("Male")),
        (GENDER_OTHER, _("Other")),
    )
    GENDER_VALID_VALUES = [choice[0] for choice in GENDER_CHOICES]
    GENDERS_DICT = {GENDER_FEMALE: GENDER_FEMALE_STRING, GENDER_MALE: GENDER_MALE_STRING, GENDER_OTHER: GENDER_OTHER_STRING}
    print(GENDERS_DICT) # for debugging.


User.ALL_GENDERS = [User.GENDERS_DICT[gender] for gender in User.GENDER_VALID_VALUES]

(它打印{1: 'female', 2: 'male', 3: 'other'}

0 个答案:

没有答案