python中没有枚举。
有人这样实现和使用:
def enum(**enums):
return type('Enum', (), enums)
使用示例:
>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
http://outofmemory.cn/code-sn...
https://stackoverflow.com/que...
其中type('Enum', (), enums)
是什么意思?谢谢
type
这种三个参数的调用,其结果是返回一个“类”,就跟用class
定义是一样的。所以,
type('Enum', (), {'ONE': 1, 'TWO': 2})
就相当于:使用上,
class
是语法层面的东西,不方便动态构造,type
就是干这事的。type
一般用在“元类”中。(“元类”实例化得到“类“)简单理解就是,
instance
<-class
<-type
,大概是这样的。