python的枚举实现中`type('Enum', (), enums)`是什么意思?
本文介绍了python的枚举实现中`type('Enum', (), enums)`是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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 Enum(object):
ONE = 1
TWO = 2
使用上, class
是语法层面的东西,不方便动态构造, type
就是干这事的。
type
一般用在元类中。(元类实例化得到类)
简单理解就是, instance
<- class
<- type
,大概是这样的。
Numbers = enum(ONE=1, TWO=2, THREE='three')
print Numbers.__name__ # Enum
这篇关于python的枚举实现中`type('Enum', (), enums)`是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文