假设以下类别:
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,我只是想知道:这里应该引发什么样的异常?在
简短的回答是^{} :
更长远的答案是,几乎没有一个类应该存在。考虑:
这将为您提供自定义枚举所做的一切:
要获得与定制的
__str__
方法相同的结果,只需使用name
属性:要使用枚举的名称获取成员,请将枚举视为dict:
使用
Enum.enum
的内置功能有几个优点:你写的代码要少得多。
您不会到处重复枚举成员的名称,因此如果您在某个时刻修改它,您不会遗漏任何内容。
enum的用户和使用它的代码的读者不需要记住或查找任何定制的方法。
如果您是从Java开始使用Python的,请务必记住:
Python Is Not Java(或者,停止编写这么多代码)
Guido1 has a time machine(或者,停止编写这么多代码)
1…或者在本例中,Ethan Furman,他是
enum
模块的作者。在相关问题 更多 >
编程相关推荐