可能重複:
What’s the best way to implement an ‘enum’ in Python?Python的枚舉相當於
是什麼(在C/C++或Java就像枚舉)Python的成語索引的不同名稱的列表?
說明:我想要一個值的屬性設置爲受限制的範圍,如卡套件Heart, Club, Spade, Diamond
。我可以用範圍爲0..3的int來表示它,但它可以允許超出範圍輸入(如15)。
可能重複:
What’s the best way to implement an ‘enum’ in Python?Python的枚舉相當於
是什麼(在C/C++或Java就像枚舉)Python的成語索引的不同名稱的列表?
說明:我想要一個值的屬性設置爲受限制的範圍,如卡套件Heart, Club, Spade, Diamond
。我可以用範圍爲0..3的int來表示它,但它可以允許超出範圍輸入(如15)。
class Suite(object): pass
class Heart(Suite): pass
class Club(Suite): pass
等
在Python類是一個對象。所以,你可以寫
x=Heart
等
這裏很受歡迎的相同問題上stackoverflow
編輯:
class Suite(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
s1 = Suite(['Heart', 'Club', 'Spade', 'Diamond'])
s1.Heart
http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python – 2010-07-14 17:42:22
相似的問題:http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an -enum功能於蟒蛇 – Jordan 2010-07-14 17:42:47