class BaseChoices object MALE FEMALE UNKNOWN CHOICES MALE MALE FEMALE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class BaseChoices(object):
MALE = 0
FEMALE = 1
UNKNOWN = 2
CHOICES = (
(MALE, "MALE"),
(FEMALE, "FEMALE"),
(UNKNOWN, "UNKNOWN"),
)
@classmethod
def get_value(cls, field):
for choice in cls.CHOICES:
if choice[0] == field:
return choice[1]
return ""
@classmethod
def get_inner_value(cls, value):
for choice in cls.CHOICES:
if choice[1] == value:
return choice[0]
return None
class BaseChoicesImproved(object):
MALE = 0
FEMALE = 1
UNKNOWN = 2
CHOICES = (
(MALE, "MALE"),
(FEMALE, "FEMALE"),
(UNKNOWN, "UNKNOWN"),
)
@classmethod
def get_value(cls, field):
return dict(cls.CHOICES)[field]
@classmethod
def get_inner_value(cls, value):
return dict(map(lambda x: (x[1], x[0]), cls.CHOICES))[value]
if __name__ == '__main__':
bc_get_value = BaseChoices.get_value(BaseChoices.FEMALE)
bci_get_value = BaseChoicesImproved.get_value(BaseChoices.FEMALE)
print bc_get_value, bci_get_value
assert bci_get_value == bci_get_value
bc_get_inner_value = BaseChoices.get_inner_value('UNKNOWN')
bci_get_inner_value = BaseChoicesImproved.get_inner_value('UNKNOWN')
print bc_get_inner_value, bci_get_inner_value
assert bc_get_inner_value == bci_get_inner_value