问题
Lets's say I have an enumerator, is it possible to get the property that follows? So if I had today=Days.Sunday
would I be able to do something like tomorrow=today.next()
?
example:
class Days(Enum):
Sunday = 'S'
Monday = 'M'
...
Saturday = 'Sa'
I know I could use tuples (like below) to do something like tomorrow=today[1]
, but I was hoping there was something built in or more elegant.
class Days(Enum):
Sunday = ('S','Monday')
Monday = ('M','Tuesday')
...
Saturday = ('Sa','Sunday')
回答1:
Absolutely.
Just add the desired functionality to your Days
class:
class Days(Enum):
Sunday = 'S'
Monday = 'M'
Tuesday = 'T'
Wednesday = 'W'
Thursday = 'Th'
Friday = 'F'
Saturday = 'Sa'
def next(self):
cls = self.__class__
members = list(cls)
index = members.index(self) + 1
if index >= len(members):
index = 0
return members[index]
and is use:
today = Days.Wednesday
print(today.next())
# Days.Thursday
回答2:
You can create a dictionary to lookup the next day like so:
In [10]: class Days(Enum):
Sun = 'Su'
Mon = 'M'
Tue = 'Tu'
Wed = 'W'
Thu = 'Th'
Fri = 'F'
Sat = 'Sa'
In [11]: days = list(Days)
In [12]: nxt = dict((day, days[(i+1) % len(days)]) for i, day in enumerate(days))
Quick test:
In [13]: nxt[Days.Tue]
Out[13]: <Days.Wed: 'W'>
In [14]: nxt[Days.Sat]
Out[14]: <Days.Sun: 'Su'>
回答3:
#ENUM CLASS
#colors
import enum
class Color(enum.Enum):
turquoise = 1
indigo = 2
magenta = 3
cyan = 4
teal = 5
azure = 6
rose = 7
amber = 8
vermillon = 9
plum = 10
russet = 11
slate = 12
def __iter__(self):
self.idx_current = self.value
return self
def __next__(self):
if (self.idx_current > 12):
return None
self.idx_current = self.idx_current + 1
return Color (self.idx_current - 1)
#CLIENT CODE
#iterate colors starting from cyan
it = iter (Color.cyan)
while True:
#print (v.get_id())
c = next (it)
if c is None:
break
print(c)
#OUTPUT
Color.cyan
Color.teal
Color.azure
Color.rose
Color.amber
Color.vermillon
Color.plum
Color.russet
Color.slate
来源:https://stackoverflow.com/questions/26577621/get-next-enumerator-constant-property