Create an abstract Enum class

后端 未结 3 616
挽巷
挽巷 2020-12-11 02:13

I\'m trying to create an abstract enum (Flag actually) with an abstract method. My final goal is to be able to create a string representation of compound enums,

3条回答
  •  攒了一身酷
    2020-12-11 02:34

    Here is a fix of the accepted answer for python 3.8. The only change is to the ABCEnumMeta. The rest is copy-pasted from the original answer to provide a runnable example. Also tested on python 3.6.2.

    from abc import abstractmethod, ABC, ABCMeta
    from enum import auto, Flag, EnumMeta
    
    
    class ABCEnumMeta(EnumMeta, ABCMeta):
        pass
    
    
    class TranslateableFlag(Flag, metaclass=ABCEnumMeta):
    
        @classmethod
        @abstractmethod
        def base(cls):
            pass
    
        def translate(self):
            base = self.base()
            if self in base:
                return base[self]
            else:
                ret = []
                for basic in base:
                    if basic in self:
                        ret.append(base[basic])
                return " | ".join(ret)
    
    
    class Students1(TranslateableFlag):
        ALICE = auto()
        BOB = auto()
        CHARLIE = auto()
        ALL = ALICE | BOB | CHARLIE
    
        @classmethod
        def base(cls):
            return {Students1.ALICE: "Alice", Students1.BOB: "Bob",
                    Students1.CHARLIE: "Charlie"}
    
    
    class Students2(TranslateableFlag):
        ALICE = auto()
        BOB = auto()
        CHARLIE = auto()
        ALL = ALICE | BOB | CHARLIE
        
    # Abstract method not defined - should raise TypeError.
    #    @classmethod
    #    def base(cls):
    #        ...
    

提交回复
热议问题