程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Enums in Python (enum)

編輯:Python

1. Use common classes to implement enumeration

In Python, enumeration is the same as the class variable we define in the object. Each class variable is an enumeration item. The way to access the enumeration item is: the class name plus the class variable.

class color():YELLOW = 1RED = 2GREEN=3PINK = 4# access enumeration itemsprint(color.YELLOW) # The output result is 1

Although this can solve the problem, it is not rigorous and not very safe, such as:

1. In the enumeration class, there should not be enumeration items (class variables) with the same key

2. It is not allowed to directly modify the value of the enumeration item outside the class

class color():YELLOW = 1YELLOW = 3 # Note that YELLOW is assigned 3 again, which will overwrite the previous 1RED = 2GREEN=3PINK = 4# access enumeration itemsprint(color.YELLOW) #3# But the value of the defined enum item can be modified externally, which should not happencolor.YELLOW = 99print(color.YELLOW) # 99

2. Use the enum module (recommended)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved