1. 程式人生 > >Python---列舉,列舉類與普通類的區別

Python---列舉,列舉類與普通類的區別

文章內容:
1.列舉類與普通類的區別,普通類的缺陷
2.列舉型別,列舉類名稱,列舉值
3.列舉之間的比較
4.列舉轉換
5.Enum和IntEnum的區別
6.如何避免列舉別名的出現

#列舉類
#列舉類不能夠例項化,例項化沒有意義
from enum import Enum

class COLOR(Enum):
    YELLOW=1
   #YELLOW=2#TypeError: Attempted to reuse key: 'YELLOW'
    GREEN=2
    BLACK=3
    RED=4
print(COLOR.YELLOW)#COLOR.YELLOW
print(type(COLOR.YELLOW))#<enum 'COLOR'>列舉型別
print(COLOR.YELLOW.value)#1
print(type(COLOR.YELLOW.value))#<class 'int'>
print(COLOR.YELLOW.name)#YELLOW
print(type(COLOR.YELLOW.name))#<class 'str'>
COLOR.YELLOW=5#AttributeError: Cannot reassign members.

#普通類
#缺陷:可變,沒有防止相同值得功能
#1
yellwo=1
green=2
black=3
red=4
#2
{'yellwo':1,'green':2,'black':3,'red':4}#可變
#3
class Color():#可變
    yellwo=1
    green=2
    black=3
    red=4

#列舉型別、列舉名稱與列舉值
from enum import Enum

class COLOR(Enum):
    YELLOW=1
    GREEN=2
    BLACK=3
    RED=4
print(COLOR.YELLOW)#COLOR.YELLOW
print(type(COLOR.YELLOW))#<enum 'COLOR'>列舉型別
print(COLOR.YELLOW.value)#1
print(type(COLOR.YELLOW.value))#<class 'int'>列舉值
print(COLOR.YELLOW.name)#YELLOW
print(type(COLOR.YELLOW.name))#<class 'str'>列舉名稱
print(COLOR['GREEN'])#COLOR.GREEN

for i in COLOR:
    print(i)
#COLOR.YELLOW
#COLOR.GREEN
#COLOR.BLACK
#COLOR.RED


#列舉之間的比較
from enum import Enum

class COLOR(Enum):
    YELLOW=1
    GREEN=2
    BLACK=3
    RED=4
result1=COLOR.GREEN==COLOR.BLACK
print(result1)#False
result2=COLOR.GREEN==COLOR.GREEN
print(result2)#True
result3=COLOR.GREEN==2
print(result3)#False
result4=COLOR.GREEN<COLOR.BLACK
print(result4)#TypeError: '<' not supported between instances of 'COLOR' and 'COLOR'
result5=COLOR.GREEN is COLOR.GREEN#身份的比較
print(result5)#True
class COLOR2(Enum):
    YELLOW=1
    GREEN=2
    BLACK=3
    RED=4
result6=COLOR.GREEN == COLOR2.GREEN#不是同一個列舉不能作比較
print(result6)#False


#列舉的注意事項
from enum import Enum

class COLOR(Enum):
    YELLOW=1
   #YELLOW=2#會報錯
    GREEN=1#不會報錯,GREEN可以看作是YELLOW的別名
    BLACK=3
    RED=4
print(COLOR.GREEN)#COLOR.YELLOW,還是會打印出YELLOW
for i in COLOR:#遍歷一下COLOR並不會有GREEN
    print(i)
#COLOR.YELLOW
#COLOR.BLACK
#COLOR.RED
#怎麼把別名遍歷出來
for i in COLOR.__members__.items():
    print(i)
#('YELLOW', <COLOR.YELLOW: 1>)
#('GREEN', <COLOR.YELLOW: 1>)
#('BLACK', <COLOR.BLACK: 3>)
#('RED', <COLOR.RED: 4>)
for i in COLOR.__members__:
    print(i)
#YELLOW
#GREEN
#BLACK
#RED


#列舉轉換
#最好在資料庫存取使用列舉的數值而不是使用標籤名字字串
#在程式碼裡面使用列舉類
a=1
print(COLOR(a))#COLOR.YELLOW


#Enum和IntEnum的區別
from enum import Enum
class COLOR1(Enum):
    YELLOW=1
    GREEN='str'
    BLACK=3
    RED=4
from enum import IntEnum
class COLOR2(IntEnum):#ValueError: invalid literal for int() with base 10: 'str'
    YELLOW=1
    GREEN='str'
    BLACK=3
    RED=4
#怎麼避免出現相同列舉值,避免別名的出現
from enum import IntEnum,unique
@unique
class COLOR3(IntEnum):#ValueError: duplicate values found in <enum 'COLOR3'>: GREEN -> YELLOW
    YELLOW=1
    GREEN=1
    BLACK=3
    RED=4

#23中設計模式
#單利模式
#設計模式的優劣