工具推荐

视频效率加速
updream

一键生成高质量推广成片

立刻MV
立刻MV

低成本歌曲 MV、视频生成

剧云
剧云

中文短剧剧本制作平台

SoundView
SoundView

字幕擦除翻译、配音口型同步

Enum 的源码

通过上面的实例可以知道通过 __members__ 可以遍历枚举类的所有成员。那为什么呢?

我们可以先来大致看看 Enum 的源码是如何实现的;Enum 在模块 enum.py 中,先来看看 Enum 类的片段

class Enum(metaclass=EnumMeta):
    """Generic enumeration.
    Derive from this class to define new enumerations.
    """

可以看到,Enum 是继承元类 EnumMeta 的;再看看 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_)

首先 __members__ 方法返回的是一个包含一个 Dict 既 Map 的 MappingProxyType,并且通过 @property 将方法 __members__(cls) 的访问方式改变为了变量的的形式,既可以直接通过 __members__ 来进行访问了

继续学习
章节
课件
捐赠

python编程入门系列图文教程

  • 评论
  • 课件下载
课件暂不提供下载,工作人员正在整理中,后期请多关注该课程~