Class: Enumeration | ./src/peak/model/enumerations.py | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
An enumeration type Defining an enumeration lets you specify a set of acceptable values
of some other primitive type, each with its own name and representation.
You can think of Python 2.3's new boolean type as an enumeration whose
values are the integers 0 and 1, with names of >>> class ThreeWay(model.Enumeration): Yes = model.enum(1) No = model.enum(0) Maybe = model.enum(-1) >>> print ThreeWay.Yes ThreeWay.Yes >>> print `ThreeWay.Yes.name` 'Yes' >>> if ThreeWay.Yes == 1: print "yes!" yes! >>> print ThreeWay['No'] ThreeWay.No >>> if 'Maybe' in ThreeWay: print "maybe!" maybe! >>> [e for e in ThreeWay] [ThreeWay.Maybe, ThreeWay.No, ThreeWay.Yes] The above class will have attributes Note: Enumeration values may be of any type. See the docs on
Enumeration Class Methods Notice that the example Subclassing and Instantiating EnumerationsIt is not necessary to specifically create an instance of an enumeration class. The mere act of defining an enumeration class causes the instances to come into existence, and be available as attributes of the class. There is only ever a fixed number of instances of an enumeration class, and even if you try to create a new instance, you will just get back one of the original ones. You can, however, subclass an enumeration class to add more values: >>> class FourWay(ThreeWay): Dunno = model.enum("wha?") >>> FourWay.No # values are inherited, but not the instances FourWay.No >>> if FourWay.Yes == ThreeWay.Yes: print "equal!" equal! >>> if FourWay.Yes is not ThreeWay.Yes: print "but not identical!" but not identical! The subclass will inherit all the same literals as its superclass,
but will have new instances encapsulating them. Thus,
|