Python does not have an enumerated type, so a Slice enumeration is emulated using a Python class: the name of the Slice enumeration becomes the name of the Python class; for each enumerator, the class contains an attribute with the same name as the enumerator. For example:
enum Fruit { Apple, Pear, Orange };
The generated Python class looks as follows:
class Fruit(object): def __init__(self, val): assert(val >= 0 and val < 3) self.value = val # ... Fruit.Apple = Fruit(0) Fruit.Pear = Fruit(1) Fruit.Orange = Fruit(2)
Each instance of the class has a value
attribute providing the integer value of the enumerator. Note that the generated class also defines a number of Python special methods, such as __str__
and __cmp__
, which we have not shown.
Given the above definitions, we can use enumerated values as follows:
f1 = Fruit.Apple f2 = Fruit.Orange if f1 == Fruit.Apple: # Compare with constant # ... if f1 == f2: # Compare two enums # ... if f2.value == Fruit.Apple.value: # Use integer values # ... elif f2.value == Fruit.Pear.value: # ... elif f2.value == Fruit.Orange.value: # ...
As you can see, the generated class enables natural use of enumerated values. The Fruit
class attributes are preinitialized enumerators that you can use for initialization and comparison. You may also instantiate an enumerator explicitly by passing its integer value to the constructor, but you must make sure that the passed value is within the range of the enumeration; failure to do so will result in an assertion failure:
favoriteFruit = Fruit(4) # Assertion failure!