Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - Overriding Enum __call__ method

I have an Enum like so:

from enum import Enum

class Animal(Enum):

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

     def talk(self):
         print(self.value)

I would like to override the __call__ method so that a call like Animal('hee-haw') returns Animals.never_heard_of or None instead of raising ValueError. I would rather avoid a try statement everytime I call the Animal.

What would be a pure Python equivalent of Enum.__call__ ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...