Python 枚举类源码解读

1. EnumMeta

一旦Enum被定义,Enum类就是最终的;它不能与其他类型( int、float等)混合。如果它有继承的__new__除非定义了新__new__否则结果类将失败。
    @staticmethod
    def _get_mixins_(bases):
        """
        返回用于创建枚举成员的类型,以及第一个继承的类型枚举类。
        bases: the tuple of bases that was given to __new__  
        """
        if not bases:
            return object, Enum

        # double check that we are not subclassing a class with existing
        # enumeration members; while we're at it, see if any other data
        # type has been mixed in so we can use the correct __new__
        member_type = first_enum = None
        for base in bases:
            if  (base is not Enum and
                    issubclass(base, Enum) and
                    base._member_names_):
                raise TypeError("Cannot extend enumerations")
        # base is now the last base in bases
        if not issubclass(base, Enum):
            raise TypeError("new enumerations must be created as "
                    "`ClassName([mixin_type,] enum_type)`")

        # get correct mix-in type (either mix-in type of Enum subclass, or
        # first base if last base is Enum)
        if not issubclass(bases[0], Enum):
            member_type = bases[0]     # first data type
            first_enum = bases[-1]  # enum type
        else:
            for base in bases[0].__mro__:
                # most common: (IntEnum, int, Enum, object)
                # possible:    (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,
                #               <class 'int'>, <Enum 'Enum'>,
                #               <class 'object'>)
                if issubclass(base, Enum):
                    if first_enum is None:
                        first_enum = base
                else:
                    if member_type is None:
                        member_type = base

        return member_type, first_enum
def __new__(metacls, cls, bases, classdict):
        member_type, first_enum = metacls._get_mixins_(bases)

猜你喜欢

转载自www.cnblogs.com/AIEIKE/p/10240225.html
今日推荐