覆盖枚举__call__方法 [英] Overriding Enum __call__ method

查看:105
本文介绍了覆盖枚举__call__方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举如下:

 从枚举导入枚举

class动物(枚举):

cat ='meow'
dog ='woof'
never_heard_of =无

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

我想要覆盖 __调用__ 方法,以便像 Animal('hee-haw')之类的调用返回 Animals.never_heard_of 而不是提高 ValueError 。每次我调用 Animal 时,我宁愿避免使用尝试语句。



什么是纯粹的Python相当于 Enum .__ call __

解决方案

更新2017-03-30



使用Python 3.6(和 aenum 2.0 1 ),你可以指定一个 _missing _ 方法,这个方法将被调用,以便在提高 ValueError 之前给你的班级最后一次机会。所以现在你可以做:

  @classmethod 
def _missing_(cls,name):
return cls .never_heard_of






原始答案 Animal()相关联的 __调用__ 实际上是在 enum.py 中的元类( EnumMeta )上。



这是一个你不想进入的蠕虫袋,因为它很容易破解。



<有关详细信息,请参见此答案,但简单的解决方案是创建一个 get 方法为$ 动物枚举:

  @classmethod 
def get(cls,name):
try:
return cls [name]
除了KeyError:
return cls.never_heard_of

然后 Animal.get('wolf')将返回 Animal.never_heard_of






1 披露:我是 Python stdlib 枚举的作者 enum34 backport 高级枚举( aenum 库。


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__ ?

解决方案

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.

这篇关于覆盖枚举__call__方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆