在元类上定义__contains__是危险的吗?

时间:2014-03-11 00:59:03

标签: python-2.7 contains metaclass

我正在Python 2.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

我想知道在元类上实现容器特定的函数(例如__contains__)是否是一件危险的事情,如果是,为什么?

0 个答案:

没有答案