获取下一个枚举器常量/属性

时间:2014-10-26 20:32:59

标签: python python-3.x enums enumeration

让我们说我有一个普查员,是否可以获得随后的财产?如果我有today=Days.Sunday,我可以做tomorrow=today.next()

之类的事情

示例:

class Days(Enum):
     Sunday = 'S'
     Monday = 'M'
     ...
     Saturday = 'Sa'

我知道我可以使用元组(如下所示)来做tomorrow=today[1]之类的事情,但我希望有一些内置或更优雅的东西。

class Days(Enum):
     Sunday = ('S','Monday')
     Monday = ('M','Tuesday')
     ...
     Saturday = ('Sa','Sunday')

4 个答案:

答案 0 :(得分:8)

绝对。

只需在Days课程中添加所需的功能:

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]

并且正在使用:

today = Days.Wednesday
print(today.next())
# Days.Thursday

答案 1 :(得分:2)

您可以创建一个字典,以便在第二天查找:

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))

快速测试:

In [13]: nxt[Days.Tue]
Out[13]: <Days.Wed: 'W'>

In [14]: nxt[Days.Sat]
Out[14]: <Days.Sun: 'Su'>

答案 2 :(得分:0)

#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

答案 3 :(得分:0)

对我来说,这似乎是没有其他功能的最优雅的解决方案

day = Days.Sunday

day = Days((day.value + 1) % len(Days) + 1) # next day cycled