Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 在元类上定义“包含”是否危险?_Python 2.7_Contains_Metaclass - Fatal编程技术网

Python 2.7 在元类上定义“包含”是否危险?

Python 2.7 在元类上定义“包含”是否危险?,python-2.7,contains,metaclass,Python 2.7,Contains,Metaclass,我正在Python2.7中编写一个自定义EnumMeta类,它将从某个类中收集枚举键和值,并使用一些附加字段来扩充该类 class EnumMeta(type): def __init__(cls, name, bases, props): cls.__all_values__ = [...] # collect all interesting properties def __contains__(cls, value): return val

我正在Python2.7中编写一个自定义EnumMeta类,它将从某个类中收集枚举键和值,并使用一些附加字段来扩充该类

class EnumMeta(type):
    def __init__(cls, name, bases, props):
        cls.__all_values__ = [...] # collect all interesting properties

    def __contains__(cls, value):
        return value in cls.__all_values__

class TheFellowshipOfTheRing(object):
    __metaclass__ = EnumMeta

    FRODO = 'Frodo Baggins'
    SAM = 'Samwise "Sam" Gamgee'
    MERRY = 'Meriadoc "Merry" Brandybuck'
    PIPPIN = 'Peregrin "Pippin" Took'
    GANDALF = 'Gandalf the Grey'
    ARAGORN = 'Aragorn (Strider)'
    LEGOLAS = 'Legolas'
    GIMLI = 'Gimli'
    BOROMIR = 'Boromir'

print 'Gandalf the Grey' in TheFellowshipOfTheRing
@ True
print 'Saruman' in TheFellowshipOfTheRing
@ False

我想知道在元类上实现特定于容器的函数(如
\uuuuu contains\uuuu
)是否是一件危险的事情,如果是这样,原因是什么?

不,这就是Python 3的
枚举
类的工作方式:。与编写自己的Enum类不同,您可能希望使用3.4版本的后端口版本:这只是实现的要点,但我有一些非常具体的要求,其中3.4 Enum不太适合。但这是一个很好的暗示。Thnx!