gpt4 book ai didi

python - 逗号分隔时 Python 枚举中的 ValueError

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:36 27 4
gpt4 key购买 nike

<分区>

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com