Python 2.7 在元类上定义“包含”是否危险?
我正在Python2.7中编写一个自定义EnumMeta类,它将从某个类中收集枚举键和值,并使用一些附加字段来扩充该类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
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!