python学习笔记(15)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值