【问题标题】:ValueError on Python Enum when comma seperated [duplicate]逗号分隔时Python枚举中的ValueError [重复]
【发布时间】:2017-02-09 09:16:54
【问题描述】:

考虑以下代码。 当逗号分隔时,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))

输出:

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

【问题讨论】:

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

标签: python


【解决方案1】:

你的第二个 sn-p 相当于这个:

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

换句话说,AppleOrange 都是长度为 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

另一个是Python的解析规则总是允许在列表中使用逗号;这对于使跨越多行的列表看起来更干净一些很有用,并允许使用例如定义单元素元组。 (1,)。您已经找到了一种组合这些规则的方法,这种方法虽然不是很有用,但不值得阻止。

【讨论】:

  • 在 c++ 中使用枚举时放置逗号是一种自然的本能。
猜你喜欢
  • 2014-03-24
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 2011-07-26
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
相关资源
最近更新 更多