Python学习(十四)--枚举类型
2020-08-06 本文已影响0人
白面葫芦娃92
1.枚举
枚举本身就是一个类
枚举的标识最好全部用大写来表示
2.枚举和普通的类有什么区别
首先思考:如何在不使用枚举类型的前提下,表示黄钻和绿钻两种类型
class TypeDiamond():
yellow = 1
green = 2
#或者
a = {'yellow':1,'green':2}
缺陷:
(1)上面两种都是可变的,在代码里都可以轻易改变他们的值
(2)没有防止相同标签的功能
例如:
a['yellow'] = 3 可以轻易的被更改值
a = {'yellow':1,'green':1} 无法防止有相同的值
枚举类型的使用方法如下:
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 2
print(VIP.GREEN)
==>
VIP.GREEN
给枚举标签赋新的值会报错
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 2
VIP.GREEN = 5
==>
Traceback (most recent call last):
File ".\c7.py", line 8, in <module>
VIP.GREEN = 5
File "C:\Users\ZouHan\Anaconda3\lib\enum.py", line 386, in __setattr__
raise AttributeError('Cannot reassign members.')
AttributeError: Cannot reassign members.
3.如何获取枚举类型标签的各类信息
(1)获取标签的值
print(VIP.YELLOW.value)
==>
1
(2)获取标签的名字
print(VIP.YELLOW.name)
==>
YELLOW
(3)print(VIP.YELLOW)有什么区别?
print(type(VIP.YELLOW.name))
print(type(VIP.YELLOW))
==>
<class 'str'>
<enum 'VIP'>
VIP.YELLOW.name的类型是个字符串,而VIP.YELLOW的类型是个枚举类型
(4)如何通过枚举类型的标签名获得枚举类型
print(VIP['GREEN'])
==>
VIP.GREEN
(5)使用数值来访问枚举类型的方式
class VIP(Enum):
YELLOW = 1
BLACK = 2
GREEN = 3
RED = 4
a = 1
print(VIP(a))
==>
VIP.YELLOW
枚举类型、枚举的名字和枚举的值这三个概念要区分清楚
4.遍历枚举类型
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
for v in VIP:
print(v)
==>
VIP.YELLOW
VIP.GREEN
VIP.BLACK
VIP.RED
5.枚举之间的比较
两个枚举之间是可以进行等值比较的
result = VIP.GREEN == VIP.YELLOW
print(result)
==>
False
result = VIP.GREEN == VIP.GREEN
print(result)
==>
True
result = VIP.GREEN == '2'
print(result)
==>
False
result = VIP.GREEN > VIP.YELLOW
print(result)
==>
Traceback (most recent call last):
File ".\c7.py", line 20, in <module>
result = VIP.GREEN > VIP.YELLOW
TypeError: '>' not supported between instances of 'VIP' and 'VIP'
#会报错,说明不能进行大小比较
result = VIP.GREEN is VIP.GREEN
print(result)
==>
True
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
class VIP1(Enum):
YELLOW = 1
GREEN = 2
BLACK = 3
RED = 4
result = VIP.GREEN == VIP1.GREEN
print(result)
==>
False
#因为两个GREEN虽然值相同,但他们属于两个不同的枚举类型,所以肯定不等值
6.枚举类型标签名不可重复
class VIP(Enum):
YELLOW = 1
BLACK = 1
GREEN = 3
RED = 4
#可以有两个类型的值相同,但是BLACK相当于YELLOW的别名,不能够成为一个独立的枚举类型
print(VIP.BLACK)
==>
VIP.YELLOW
for v in VIP:
print(v)
==>
VIP.YELLOW
VIP.GREEN
VIP.RED
#别名不会打印出来
那么有没有办法把别名也打印出来么?
for v in VIP.__members__.items():
print(v)
==>
('YELLOW', <VIP.YELLOW: 1>)
('BLACK', <VIP.YELLOW: 1>)
('GREEN', <VIP.GREEN: 3>)
('RED', <VIP.RED: 4>)
-----------------------------------------------------
for v in VIP.__members__:
print(v)
==>
YELLOW
BLACK
GREEN
RED
7.上面的枚举类型 YELLOW = '1'也可以
但是如果继承了IntEnum:
from enum import IntEnum
class VIP(IntEnum):
YELLOW = 1
BLACK = '2' # 会报错,因为必须为int类型
GREEN = 3
RED = 4
之前两个枚举类型标签的值相同不会报错
class VIP(Enum):
YELLOW = 1
BLACK = 1
GREEN = 3
RED = 4
#不会报错,如果想让它报错,可以用unique装饰器
from enum import IntEnum,unique
@unique
class VIP(IntEnum):
YELLOW = 1
BLACK = 1
GREEN = 3
RED = 4
枚举是单例的形式实现的,是不能实例化的(需了解一下23种设计模式之单例模式)