考虑下面的代码。逗号分隔时,Python如何解释类RottenFruit?这合法吗?如果是,用例是什么?
from enum import Enum
class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6
a = Fruit(5)
class RottenFruit(Enum):
Apple = 4,
Orange = 5,
Pear = 6
print(Fruit(5))
print(RottenFruit(5))
Run Code Online (Sandbox Code Playgroud)
输出:
Fruit.Orange
Traceback (most recent call last):
File "...\tests\sandbox.py", line 15, in <module>
print(RottenFruit(5))
File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 291, in __call__
return cls.__new__(cls, value)
File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 533, in __new__
return cls._missing_(value)
File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 546, in _missing_
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 5 is not a valid RottenFruit
Run Code Online (Sandbox Code Playgroud)
您的第二个代码段与此等效:
class RottenFruit(Enum):
Apple = (4,)
Orange = (5,)
Pear = 6
Run Code Online (Sandbox Code Playgroud)
换句话说,Apple和Orange是每个长度为1的元组。
让我添加一个简短的解释。您在这里遇到了两个Python功能的组合。一种是您可以一次分配多项,例如:
x = 7
y = 8
y, x = x, y # Now x = 8 and y = 7
q = [1, 2, 3, 4, 5]
x, m, *r, y = q # Even fancier: now x = 1, m = 2, r = [3, 4] and y = 5
Run Code Online (Sandbox Code Playgroud)
另一个是Python的解析规则始终在列表中允许尾随逗号。这对于使跨越多行的列表看起来更简洁很有用,并且允许使用例如定义一个元素的元组(1,)。您已经找到了一种将这些规则组合在一起的方法,该方法虽然没有什么实际用处,但值得防止。