Possible Duplicate:
How can I represent an 'enum' in Python?
What's the common practice for enums in Python? I.e. how are they replicated in Python?
public enum Materials { Shaded, Shiny, Transparent, Matte }
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.
By definition, the enumeration member values are unique. However, you can create different member names with the same values.
Use Enum Members in DictionariesPython enumerations are hashable. This means you can use the enumeration members in dictionaries.
class Materials: Shaded, Shiny, Transparent, Matte = range(4) >>> print Materials.Matte 3
I've seen this pattern several times:
>>> class Enumeration(object): def __init__(self, names): # or *names, with no .split() for number, name in enumerate(names.split()): setattr(self, name, number) >>> foo = Enumeration("bar baz quux") >>> foo.quux 2
You can also just use class members, though you'll have to supply your own numbering:
>>> class Foo(object): bar = 0 baz = 1 quux = 2 >>> Foo.quux 2
If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With