python learning Notes (16) python enumeration class

enum class in python

Enumeration: in mathematics and computer science in theory, a set of enumeration lists all the members of some finite sequence of sets of program

Examples are as follows:

from enum import Enum

class traffictlight(Enum):     #继承枚举类,枚举成员不可重复
    RED=1       #枚举成员    RED是枚举的名字,1是枚举的值
    YELLOW=2
    GREEN=3
    
#枚举成员的比较    print(traffictlight.YELLOW.value == 1)   返回True
    
print(type(traffictlight.YELLOW))
print(traffictlight.YELLOW.name)
print(traffictlight.YELLOW.value)
print(traffictlight(2))            #通过枚举值获取枚举成员


def judge(color):
  if color ==traffictlight.RED or color==traffictlight.YELLOW:   
      print("司机超速")
  else:
    print("正常行驶")


judge(traffictlight.GREEN)

#输出:

<enum'traffictlight'>
YELLOW
2
traffictlightYELLOW
正常行驶
Published 29 original articles · won praise 3 · Views 655

Guess you like

Origin blog.csdn.net/weixin_45574790/article/details/104573339