[Python] Is it possible to define a class constant inside an Enum?

Discussão em 'Python' iniciado por Stack, Agosto 26, 2025.

  1. Stack

    Stack Membro Participativo

    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 it can be extended:

    >>> class Planet(Enum):
    ... MERCURY = (3.303e+23, 2.4397e6)
    ... VENUS = (4.869e+24, 6.0518e6)
    ... EARTH = (5.976e+24, 6.37814e6)
    ... MARS = (6.421e+23, 3.3972e6)
    ... JUPITER = (1.9e+27, 7.1492e7)
    ... SATURN = (5.688e+26, 6.0268e7)
    ... URANUS = (8.686e+25, 2.5559e7)
    ... NEPTUNE = (1.024e+26, 2.4746e7)
    ... def __init__(self, mass, radius):
    ... self.mass = mass # in kilograms
    ... self.radius = radius # in meters
    ... @property
    ... def surface_gravity(self):
    ... # universal gravitational constant (m3 kg-1 s-2)
    ... G = 6.67300E-11
    ... return G * self.mass / (self.radius * self.radius)
    ...
    >>> Planet.EARTH.value
    (5.976e+24, 6378140.0)
    >>> Planet.EARTH.surface_gravity
    9.802652743337129


    This example also demonstrates a problem with Enum: in the surface_gravity() property method, a constant G is defined which would normally be defined at class level - but attempting to do so inside an Enum would simply add it as one of the members of the enum, so instead it's been defined inside the method.

    If the class wanted to use this constant in other methods, it'd have to be defined there as well, which obviously isn't ideal.

    Is there any way to define a class constant inside an Enum, or some workaround to achieve the same effect?

    Continue reading...

Compartilhe esta Página