可以使用Python枚举中的命名参数吗? [英] Can named arguments be used with Python enums?

查看:176
本文介绍了可以使用Python枚举中的命名参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

class Planet(Enum):

    MERCURY = (mass: 3.303e+23, radius: 2.4397e6)

    def __init__(self, mass, radius):
        self.mass = mass       # in kilograms
        self.radius = radius   # in meters

参考: https://docs.python.org/3/library/enum.html#planet

为什么要这样做?如果构造函数列表中有几个基本类型(int,bool),那么使用命名参数就会很好。

Why do I want to do this? If there are a few primitive types (int, bool) in the constructor list, it would be nice to used named arguments.

推荐答案

虽然您不能以枚举的形式使用命名参数,但您可以使用 namedtuple mixin:

While you can't use named arguments the way you describe with enums, you can get a similar effect with a namedtuple mixin:

from collections import namedtuple
from enum import Enum

Body = namedtuple("Body", ["mass", "radius"])

class Planet(Body, Enum):

    MERCURY = Body(mass=3.303e+23, radius=2.4397e6)
    VENUS   = Body(mass=4.869e+24, radius=6.0518e6)
    EARTH   = Body(mass=5.976e+24, radius=3.3972e6)
    # ... etc.

...在我心里很清洁,因为你不需要写一个 __ init __ 方法。

... which to my mind is cleaner, since you don't have to write an __init__ method.

使用示例:

>>> Planet.MERCURY
<Planet.MERCURY: Body(mass=3.303e+23, radius=2439700.0)>
>>> Planet.EARTH.mass
5.976e+24
>>> Planet.VENUS.radius
6051800.0

请注意,根据文档,混合类型必须在枚举之前出现在基地的顺序。

Note that, as per the docs, "mix-in types must appear before Enum itself in the sequence of bases".

这篇关于可以使用Python枚举中的命名参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆