from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED == 1) # False
for color in Color:
print(color)
print(Color(1)) # Color.RED
print(Color['RED']) # Color.RED
print(Color(1).name) # RED
print(Color.RED.value) # 1
# odict_items([('RED', <Color.RED: 1>), ('GREEN', <Color.GREEN: 2>), ('BLUE', <Color.BLUE: 3>)])
print(Color.__members__.items())
print(Color(1) == Color.RED) # True
#print(Color(2) > Color(1)) # TypeError, cannot implement greater-than and less-than comparison
#Color(1).value = 10 #AttributeError, cannot set attribute
# define Animal
Animal = Enum('Animal', 'ANT BEE CAT DOG')
print(list(Animal)) #[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
from enum import Enum, unique
# enum allows different names have same value
class Mistake(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
# decorator unique guarrantee all values are unique
# if more than one names have same value, throw ValueError
@unique
class Mistake2(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
from enum import Enum, auto
class Color(Enum):
RED = auto()
BLUE = auto()
GREEN = auto()
print(list(Color)) # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
from enum import IntEnum
class Shape(IntEnum):
CIRCLE = 1
SQUARE = 2
print(Shape.CIRCLE == 1) # True
from enum import IntFlag
class Perm(IntFlag):
R = 4
W = 2
X = 1
a = Perm.R | Perm.W # Perm.R|W
print(a.value) # 6
b = Perm.R + Perm.W
print(b) # 6
from enum import Flag, auto
class Color(Flag):
RED = auto()
BLUE = auto()
GREEN = auto()
print(list(Color)) # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>]
b = Color.RED & Color.GREEN # Color.0