我主要是C#開發人員,但目前正在使用Python開發項目。 html
我怎樣才能表明Python中的Enum? python
def M_add_class_attribs(attribs): def foo(name, bases, dict_): for v, k in attribs: dict_[k] = v return type(name, bases, dict_) return foo def enum(*names): class Foo(object): __metaclass__ = M_add_class_attribs(enumerate(names)) def __setattr__(self, name, value): # this makes it read-only raise NotImplementedError return Foo()
像這樣使用它: ide
Animal = enum('DOG', 'CAT') Animal.DOG # returns 0 Animal.CAT # returns 1 Animal.DOG = 2 # raises NotImplementedError
若是您只須要惟一的符號而且不關心值,請替換此行: ui
__metaclass__ = M_add_class_attribs(enumerate(names))
有了這個: this
__metaclass__ = M_add_class_attribs((object(), name) for name in names)
最佳的解決方案取決於您從假 enum
要求。 idea
簡單枚舉: spa
若是您只須要enum
來標識不一樣項的名稱列表,那麼馬克·哈里森 (上述)的解決方案就很棒: .net
Pen, Pencil, Eraser = range(0, 3)
使用range
還能夠設置任何起始值 : 設計
Pen, Pencil, Eraser = range(9, 12)
除上述內容外,若是您還要求這些項目屬於某種容器 ,則將它們嵌入一個類中: code
class Stationery: Pen, Pencil, Eraser = range(0, 3)
要使用枚舉項目,您如今須要使用容器名稱和項目名稱:
stype = Stationery.Pen
複合枚舉:
對於一長串的枚舉或更復雜的枚舉使用,這些解決方案將沒法知足要求。 您能夠參考《 Will Ware在Python Cookbook中發佈的Python 模擬枚舉 》中的食譜 。 該版本的在線版本可在此處得到 。
更多信息:
PEP 354:Python枚舉中有一個有趣的細節,建議使用Python枚舉,以及爲何拒絕該枚舉。
雖然最初的枚舉建議PEP 354在幾年前被拒絕,但它仍在繼續提出。 原本打算將某種枚舉添加到3.2,可是將其推回到3.3,而後被遺忘了。 如今有一個PEP 435,打算包含在Python 3.4中。 PEP 435的參考實現是flufl.enum
。
截至2013年4月,彷佛已經達成了廣泛共識,即應該在3.4的標準庫中添加一些內容 ,只要人們能夠就該「內容」達成共識。 那是困難的部分。 請參閱此處和此處開始的主題以及2013年前幾個月的其餘六個主題。
同時,每次出現這種狀況時,都會在PyPI,ActiveState等上出現大量新設計和實現,所以,若是您不喜歡FLUFL設計,請嘗試進行PyPI搜索 。
在2013-05-10上,Guido贊成將PEP 435接受到Python 3.4標準庫中。 這意味着Python終於內置了對枚舉的支持!
有一個適用於Python 3.三、3.二、3.一、2.七、2.六、2.5和2.4的反向端口。 在Pypi上爲enum34 。
宣言:
>>> from enum import Enum >>> class Color(Enum): ... red = 1 ... green = 2 ... blue = 3
表示:
>>> print(Color.red) Color.red >>> print(repr(Color.red)) <Color.red: 1>
迭代:
>>> for color in Color: ... print(color) ... Color.red Color.green Color.blue
程序訪問:
>>> Color(1) Color.red >>> Color['blue'] Color.blue
有關更多信息,請參閱建議 。 官方文檔可能很快就會發布。
Python的新標準是PEP 435 ,所以Enum類將在未來的Python版本中可用:
>>> from enum import Enum
可是,如今就開始使用它,您能夠安裝激發PEP的原始庫 :
$ pip install flufl.enum
而後,您能夠根據其在線指南使用它 :
>>> from flufl.enum import Enum >>> class Colors(Enum): ... red = 1 ... green = 2 ... blue = 3 >>> for color in Colors: print color Colors.red Colors.green Colors.blue