Documentation for Ice 3.4. The latest release is Ice 3.7. Refer to the space directory for other releases.

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

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:

Slice
enum Fruit { Apple, Pear, Orange };

The generated Python class looks as follows:

Python
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:

Python
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:

Python
favoriteFruit = Fruit(4) # Assertion failure!
See Also
  • No labels