Eunm的源码
Eunm在enum.py模块中,Eunm是继承EnumMeta的。
Enmm类:
class Enum(metaclass=EnumMeta):
"""Generic enumeration.
Derive from this class to define new enumerations.
"""
EnumMeta类:
class EnumMeta(type):
"""Metaclass for Enum"""
@property
def __members__(cls):
"""Returns a mapping of member name->value.
This mapping lists all enum members, including aliases. Note that this
is a read-only view of the internal mapping.
"""
return MappingProxyType(cls._member_map_)
首先通过__member__方法返回一个包含一个Dict即Map的MappingProxyType,并通过@property将方法__member__(cls)的访问方式改变为变量的形式。
自定义枚举类
当需要控制枚举类的类时候,我们可以Enum派生出自定义类来完成。
例子:
#!/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)
结果:
Month.Jan ---------- Jan ---------- January
Jan ---------- Month.Jan ---------- January
Feb ---------- Month.Feb ---------- February
Mar ---------- Month.Mar ---------- March
Apr ---------- Month.Apr ---------- April
May ---------- Month.May ---------- May
Jun ---------- Month.Jun ---------- June
Jul ---------- Month.Jul ---------- July
Aug ---------- Month.Aug ---------- August
Sep ---------- Month.Sep ---------- September
Oct ---------- Month.Oct ---------- October
Nov ---------- Month.Nov ---------- November
Dec ---------- Month.Dec ---------- December