python enums with attributes

后端 未结 4 1140
自闭症患者
自闭症患者 2020-12-01 12:52

Consider:

class Item:
   def __init__(self, a, b):
       self.a = a
       self.b = b

class Items:
    GREEN = Item(\'a\', \'b\')
    BLUE = Item(\'c\', \'         


        
4条回答
  •  执笔经年
    2020-12-01 13:10

    Python 3.4 has a new Enum data type (which has been backported as enum34 and enhanced as aenum1). Both enum34 and aenum2 easily support your use case:

    [aenum py2/3]

    import aenum
    class EnumWithAttrs(aenum.AutoNumberEnum):
        _init_ = 'a b'
        GREEN = 'a', 'b'
        BLUE = 'c', 'd'
    

    [enum34 py2/3 or stdlib enum 3.4+]

    import enum
    class EnumWithAttrs(enum.Enum):
    
        def __new__(cls, *args, **kwds):
            value = len(cls.__members__) + 1
            obj = object.__new__(cls)
            obj._value_ = value
            return obj
    
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        GREEN = 'a', 'b'
        BLUE = 'c', 'd'
    

    And in use:

    --> EnumWithAttrs.BLUE
    
    
    --> EnumWithAttrs.BLUE.a
    'c'
    

    1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

    2 aenum also supports NamedConstants and metaclass-based NamedTuples.

提交回复
热议问题