Update 2017-03-30
With Python 3.6 (and aenum 2.0
1) you can specify a _missing_
method that will be called to give your class one last chance before raising ValueError
. So now you can do:
@classmethod
def _missing_(cls, name):
return cls.never_heard_of
Original Answer
To be clear: you want the __call__
that is associated with Animal()
which is actually on the metaclass (EnumMeta
in enum.py
).
This is a bag of worms you don't want to get in to, as it is very easy to break things.
See this answer for more details, but the simple solution is to create a get
method for your Animal
enum:
@classmethod
def get(cls, name):
try:
return cls[name]
except KeyError:
return cls.never_heard_of
and then Animal.get('wolf')
will return Animal.never_heard_of
.
1 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…