sixtstorm1 sixtstorm1 - 7 months ago 61
Python Question

How to define custom properties in enumeration in Python (Javascript-like)

In JavaScript we can do this:

var Color = {
YELLOW: { value: 1, displayString: "Yellow" },
GREEN: { value: 2, displayString: "Green" },

So I can call:


In Java we can do this:

public enum Color {

YELLOW (1, "Yellow"),
GREEN (2, "Green"),

private Color(String value, int displayString){
this.value = value;
this.displayString = displayString;

private final int value;
private final String displayString;

public String getValue() {return value;}
public String getDisplayString() {return displayString;}

So I can call:


After much research I haven't found a clean way to do this in Python using the built-in Enum module. How can I do this?



There are two concepts involved here: enumerations and attribute-style access to object members that can be initialised inline. For the latter, you'll need some kind of custom class, but since you want something very straightforward, a namedtuple is sufficient for that. So, combining namedtuple and enum, this could be a solution:

from enum import Enum
from collections import namedtuple

Color = namedtuple('Color', ['value', 'displayString'])

class Colors(Enum):

    def displayString(self):
        return self.value.displayString

    yellow = Color(1, 'Yellow')
    green = Color(2, 'Green')