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

后端 未结 5 961
感情败类
感情败类 2020-11-27 15:51

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

5条回答
  •  情深已故
    2020-11-27 16:37

    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
    
    

提交回复
热议问题