对未知枚举值引发什么类型的异常?

2024-09-30 04:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

假设以下类别:

class PersistenceType(enum.Enum):
  keyring = 1
  file = 2

  def __str__(self):
    type2String = {PersistenceType.keyring: "keyring", PersistenceType.file: "file"}
    return type2String[self]

  @staticmethod
  def from_string(type):
    if (type == "keyring" ):
        return PersistenceType.keyring
    if (type == "file"):
        return PersistenceType.file
    raise ???

作为一个pythonnoob,我只是想知道:这里应该引发什么样的异常?在


Tags: selfreturnifdeftypeenum类别class
1条回答
网友
1楼 · 发布于 2024-09-30 04:34:27

简短的回答是^{}

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

更长远的答案是,几乎没有一个类应该存在。考虑:

class PersistenceType(enum.Enum):
    keyring = 1
    file = 2

这将为您提供自定义枚举所做的一切:

  • 要获得与定制的__str__方法相同的结果,只需使用name属性:

    >>> PersistenceType.keyring.name
    'keyring'
    
  • 要使用枚举的名称获取成员,请将枚举视为dict:

    >>> PersistenceType['keyring']
    <PersistenceType.keyring: 1>
    

使用Enum.enum的内置功能有几个优点:

  1. 你写的代码要少得多。

  2. 您不会到处重复枚举成员的名称,因此如果您在某个时刻修改它,您不会遗漏任何内容。

  3. enum的用户和使用它的代码的读者不需要记住或查找任何定制的方法。

如果您是从Java开始使用Python的,请务必记住:

Python Is Not Java(或者,停止编写这么多代码)

Guido1 has a time machine(或者,停止编写这么多代码)


1…或者在本例中,Ethan Furman,他是enum模块的作者。在

相关问题 更多 >

    热门问题