获取下一个枚举器常量/属性 [英] Get next enumerator constant/property
本文介绍了获取下一个枚举器常量/属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
today = Days.Sunday
,我可以做一些类似 tomorrow = today.next()
? 示例:
class Days(Enum):
星期日='S'
星期一='M'
...
星期六='Sa'
我知道我可以使用元组(如下所示)来执行类似 tomorrow = today [1]
的内容,但我希望在是内置的或更优雅的东西。
class Days(枚举):
星期日=('S'
$ / code >
解决方案
绝对。
只需在天添加所需的功能
类:
$($)code
星期日='S'
星期一='M'
星期二='T'
星期三='W'
星期四='Th'
星期五='F'
星期六='Sa'
def next(self):
cls = self .__ class__
members = list(cls)
index = members.index(self)+ 1
if index> = len(members):
index = 0
返回成员[index]
并使用:
today = Days.Wednesday
print(today.next())
#Days.Thursday
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')
解决方案
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
这篇关于获取下一个枚举器常量/属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文