python enums with attributes

后端 未结 4 1146
自闭症患者
自闭症患者 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条回答
  •  萌比男神i
    2020-12-01 12:56

    Here's another approach which I think is simpler than the others, but allows the most flexibility:

    from collections import namedtuple
    from enum import Enum
    
    class Status(namedtuple('Status', 'name description'), Enum):
        READY = 'ready', 'I am ready to do whatever is needed'
        ERROR = 'error', 'Something went wrong here'
    
        def __str__(self) -> str:
            return self.name
    

    Works as expected:

    print(Status.READY)
    print(repr(Status.READY))
    print(Status.READY.description)
    print(Status.READY.value)
    

    prints:

    ready
    
    I am ready to do whatever is needed
    Status(name='ready', description='I am ready to do whatever is needed')
    

    You get the best of namedtuple and Enum.

提交回复
热议问题