Python 3.4 introduces a new module enum, which adds an enumerated type to the language. The documentation for enum.Enum
provides an example to demonstrate how i
A property can be used to provide most of the behaviour of a class constant:
class Planet(Enum):
# ...
@property
def G(self):
return 6.67300E-11
# ...
@property
def surface_gravity(self):
return self.G * self.mass / (self.radius * self.radius)
This would be a little unwieldy if you wanted to define a large number of constants, so you could define a helper function outside the class:
def constant(c):
"""Return a class property that returns `c`."""
return property(lambda self: c)
... and use it as follows:
class Planet(Enum):
# ...
G = constant(6.67300E-11)
One limitation of this approach is that it will only work for instances of the class, and not the class itself:
>>> Planet.EARTH.G
6.673e-11
>>> Planet.G