所有基础文章修改完毕
This commit is contained in:
47
Article/PythonBasis/python11/3.md
Normal file
47
Article/PythonBasis/python11/3.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# 三、自定义类型的枚举 #
|
||||
|
||||
但有些时候我们需要控制枚举的类型,那么我们可以 Enum 派生出自定义类来满足这种需要。通过修改上面的例子:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
from enum import Enum, unique
|
||||
|
||||
Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
|
||||
|
||||
|
||||
# @unique 装饰器可以帮助我们检查保证没有重复值
|
||||
@unique
|
||||
class Month(Enum):
|
||||
Jan = 'January'
|
||||
Feb = 'February'
|
||||
Mar = 'March'
|
||||
Apr = 'April'
|
||||
May = 'May'
|
||||
Jun = 'June'
|
||||
Jul = 'July'
|
||||
Aug = 'August'
|
||||
Sep = 'September '
|
||||
Oct = 'October'
|
||||
Nov = 'November'
|
||||
Dec = 'December'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(Month.Jan, '----------',
|
||||
Month.Jan.name, '----------', Month.Jan.value)
|
||||
for name, member in Month.__members__.items():
|
||||
print(name, '----------', member, '----------', member.value)
|
||||
|
||||
```
|
||||
|
||||
|
||||
输出的结果如下:
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
通过上面的例子,可以知道枚举模块定义了具有迭代 (interator) 和比较(comparison) 功能的枚举类型。 它可以用来为值创建明确定义的符号,而不是使用具体的整数或字符串。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user