python enums with attributes

后端 未结 4 1148
自闭症患者
自闭症患者 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:02

    For Python 3:

    class Status(Enum):
        READY = "ready", "I'm ready to do whatever is needed"
        ERROR = "error", "Something went wrong here"
    
        def __new__(cls, *args, **kwds):
            obj = object.__new__(cls)
            obj._value_ = args[0]
            return obj
    
        # ignore the first param since it's already set by __new__
        def __init__(self, _: str, description: str = None):
            self._description_ = description
    
        def __str__(self):
            return self.value
    
        # this makes sure that the description is read-only
        @property
        def description(self):
            return self._description_
    

    And you can use it as a standard enum or factory by type:

    print(Status.READY)
    # ready
    print(Status.READY.description)
    # I'm ready to do whatever is needed
    print(Status("ready")) # this does not create a new object
    # ready
    

提交回复
热议问题