El_*_*ado 7 python enums python-3.x
当我学习 Python 中的概念时,我遇到了这个枚举模块。我尝试了下面的代码:
import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = "raj"
   Tue = 3
   Wed= 123
   Thur=12312312
   Fri=1312312
   Sat=12122135435
   
# print the enum member as a string
print("The enum member as a string is : ",end="")
print(Days.Mon)
# print the enum member as a repr
print("he enum member as a repr is : ",end="")
print(repr(Days.Sun))
print(repr(Days.fri))
# Check type of enum member
print("The type of enum member is : ",end ="")
print(type(Days.Mon))
# Accessing enums by names or values
print(Days['Mon'])
print(Days(3))
print(Days['thur'])
print(Days['thur'] == "thur")
print(Days(12122135435) == "sat" )
# print name of enum member
print("The name of enum member is : ",end ="")
print(Days.Tue.name)
输出:
Days.Mon
he enum member as a repr is : <Days.Sun: 1>
<Days.fri: 1312312>
The type of enum member is : <enum 'Days'>
Days.Mon
Days.Tue
Days.thur
False
False
The name of enum member is: Tue
下面是简单的类和类变量访问:
class Raj:
    yoo = 1
    boo = "raj"
    too = 213
    
print(Raj.yoo)
print(Raj.boo)
print(Raj.too)
class Materials:
    Shaded, Shiny, Transparent, Matte = range(1, 5)
    
print(Materials.Matte)
print(Materials.Transparent)
输出:
1
raj
213
4
3
当我们可以简单地使用类变量并调用它们来获取值时,我无法理解枚举的用例是什么。枚举函数只返回我们要求打印的内容,如果我们按值调用则返回名称。正如您在上面的代码中看到的那样,我试图Days['thur'] == "thur"通过像这样的调用来匹配我认为的返回,它返回的是名称,但不是。所以尝试像Days(12122135435) == "sat"这样调用,以便我可以获得值的名称并且可以匹配。但不。
我很困惑为什么要定义它以及为什么要使用它?
Enum 类型来自 C 和 C++ 等语言。动机解释如下:
枚举是一种用户定义的类型,由一组称为枚举器的命名常量组成。这个想法是,不使用 int 来表示一组值,而是使用具有一组受限值的类型。...[使用整数表示彩虹颜色]的问题是整数比颜色多得多。如果 violet 的值为 7,并且程序将值 15 分配给变量,那么这显然是一个错误 - 但可能不会被检测到,因为 15 是 int 的有效值。...使用枚举可以提高抽象级别,让程序员思考这些值的含义,而不是担心它们如何存储和访问。这减少了错误的发生。
枚举有以下好处:
- 它们限制枚举变量可以采用的值。
- 它们迫使您考虑枚举可以采用的所有可能值。
- 它们是常数而不是数字,增加了源代码的可读性
交通灯就是一个很好的例子:
from enum import Enum   
class TrafficLights(Enum):
    red = 4  # 4 is the bit representation
    red_yellow = 6
    green = 1
    yellow = 2
print(TrafficLights.yellow)
print(TrafficLights(2))
print(repr(TrafficLights.yellow))
# Looking at object attributes
print(dir(TrafficLights.yellow))
# Accessing value by name
print(TrafficLights.yellow.value)
for light in TrafficLights:
    print(light)
请注意,交通信号灯具有特定的位表示形式,并且不能采用任何其他值。此外,该类是可迭代的,并且可以通过名称或值访问项目,这对于常规属性来说是不可能的。
底线是,enum这不是一个必需的模块,但拥有它还是很不错的。它对于需要一组有限的枚举对象的特定用例非常有用。
从文档中
枚举是一组绑定到唯一常量值的符号名称(成员)
关键字绑定到唯一且恒定的值。
说你有
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
和
>>> class ColorClass():
...     RED = 1
...     GREEN = 2
...     BLUE = 3
你可以这样做
>>> ColorClass.RED = 3
>>>
但当你这样做时
>>> Color.RED = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Programme\Python37\lib\enum.py", line 386, in __setattr__
    raise AttributeError('Cannot reassign members.')
AttributeError: Cannot reassign members.
你得到
属性错误:无法重新分配成员。
| 归档时间: | 
 | 
| 查看次数: | 3499 次 | 
| 最近记录: |