Create an abstract Enum class

后端 未结 3 632
挽巷
挽巷 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:37

    If the goal is simply to change the __str__ output of Students1, you do not need to use abstract classes:

    from enum import auto, Flag
    from functools import reduce
    
    class TranslateableFlag(Flag):
    
        def __init__(self, value):
            self.translated = self.name.title()
    
        def __str__(self):
            cls = self.__class__
            total = self._value_
            i = 1
            bits = set()
            while i <= total:
                bits.add(i)
                i *= 2
            members = [m for m in cls if m._value_ in bits]
            return '%s' % (
                    ' | '.join([str(m.translated) for m in members]),
                    )
    
    class Students1(TranslateableFlag):
        ALICE = auto()
        BOB = auto()
        CHARLIE = auto()
        ALL = ALICE | BOB | CHARLIE
    

    and in use:

    >>> print(Students1.ALICE | Students1.BOB)
    Alice | Bob
    
    >>> print(Students1.ALL)
    Alice | Bob | Charlie
    

提交回复
热议问题