2012-10-01 35 views
4

蟒蛇枚舉考慮:與屬性

class Item: 
    def __init__(self, a, b): 
     self.a = a 
     self.b = b 

class Items: 
    GREEN = Item('a', 'b') 
    BLUE = Item('c', 'd') 

是否有一個用於簡單枚舉的思想適應這種情況呢? (請參閱this question)理想情況下,與Java一樣,我想將它全部整合到一個類中。

Java模型:

enum EnumWithAttrs { 
    GREEN("a", "b"), 
    BLUE("c", "d"); 

    EnumWithAttrs(String a, String b) { 
     this.a = a; 
     this.b = b; 
    } 

    private String a; 
    private String b; 

    /* accessors and other java noise */ 
} 
+5

你試圖做的事情根本不清楚「將簡單枚舉的想法適應於這種情況」。 – kindall

+0

你會如何在Java中做到這一點? – NullUserException

+2

也許使用[命名元組](http://docs.python.org/library/collections.html#collections.namedtuple)?但是,再次,不,最好使用類來代替。 –

回答

6

的Python 3.4擁有new Enum data type(這一直backported as enum34enhanced as aenum )。無論enum34aenum 輕鬆支持你的使用情況:

[aenum PY2/3]

import aenum 
class EnumWithAttrs(aenum.AutoNumberEnum): 
    _init_ = 'a b' 
    GREEN = 'a', 'b' 
    BLUE = 'c', 'd' 

[enum34 PY2/3或stdlib enum 3.4+]

import enum 
class EnumWithAttrs(enum.Enum): 

    def __new__(cls, *args, **kwds): 
     value = len(cls.__members__) + 1 
     obj = object.__new__(cls) 
     obj._value_ = value 
     return obj 

    def __init__(self, a, b): 
     self.a = a 
     self.b = b 

    GREEN = 'a', 'b' 
    BLUE = 'c', 'd' 

而且在使用:

--> EnumWithAttrs.BLUE 
<EnumWithAttrs.BLUE: 1> 

--> EnumWithAttrs.BLUE.a 
'c' 

披露:我是Python stdlib Enum的作者,enum34 backportAdvanced Enumeration (aenum)庫。

aenum還支持NamedConstants和元類爲主NamedTuples

+0

自定義枚舉的鏈接已死亡。查看Python的聲明Planet枚舉的方式:https://docs.python.org/3/library/enum.html#planet – Risadinha

+0

@Risadinha:刪除了死鏈接,更新了代碼示例。 –

3

使用namedtuple

from collections import namedtuple 

Item = namedtuple('abitem', ['a', 'b']) 

class Items: 
    GREEN = Item('a', 'b') 
    BLUE = Item('c', 'd') 
+0

顯然我需要在這裏做一些閱讀。 – bmargulies

+0

@bmargulies或者一些觀看。在PyCon談話的視頻錄製中] Raymond Hettinger解釋了爲什麼命名元組非常棒,他們是如何工作的以及他們的用例。 [使用Python的較新工具](http://pyvideo.org/video/367/pycon-2011--fun-with-python--39-s-newer-tools)'[11:35 - 26:00] '。他演示的例子包括顏色的枚舉類型。 –