Overriding Enum __call__ method

后端 未结 1 2003
日久生厌
日久生厌 2020-12-12 00:11

I have an Enum like so:

from enum import Enum

class Animal(Enum):

     cat = \'meow\'
     dog = \'woof\'
     never_heard_of = None

     def         


        
相关标签:
1条回答
  • 2020-12-12 00:23

    Update 2017-03-30

    With Python 3.6 (and aenum 2.01) 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.

    0 讨论(0)
提交回复
热议问题