2017-02-09 32 views
1

请考虑以下代码。 python在用逗号分隔时如何解释类​​RottenFruit?这合法吗?如果是,那么用例是什么?Python上的ValueError枚举(逗号分隔)

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)) 

输出:

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 
+0

我不同意“搁置作为题外话”评估。 OP询问他们为什么不会因为使用逗号而得到简单的语法错误。这很有趣,我一开始也不明白。编辑:现在它已被标记为重复,但没有链接到所谓的原始问题。 –

回答

2

你的第二片段是等效于这样的:

class RottenFruit(Enum): 
    Apple = (4,) 
    Orange = (5,) 
    Pear = 6 

换言之,AppleOrange是长度一个的每个元组。

让我来添加一个快速解释。您在这里遇到了两个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 

另一种是,Python的解析规则总是允许列表中的一个尾随逗号;这对跨越多行的列表看起来更干净一些,并且允许用一个元素定义一个元素的元组很有用。 (1,)。你已经找到了一种方式来组合这些规则,但这种方式并不是很有用,但不值得预防。

+0

在C++中使用枚举的时候,它将自然的本能放在逗号中。 – goldcode