例子:

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),最好使用命名参数.

推荐答案

虽然不能像使用枚举描述的那样使用命名参数,但使用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__方法.

示例用法:

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

请注意,根据the docs,"混合类型必须以碱基顺序出现在Enum之前".

Python-3.x相关问答推荐

如何在Python Matplotlib中在x轴上放置点

Python网页抓取:代码输出:汤未定义

谁能解释一下这个带邮编的多功能环路?

将列表项的极列水平分解为新列

为什么我在BLE中的广告代码在发送包裹之间需要大约1秒

如何使用正则表达式通过反向搜索从链接中获取特定文本

使用 iloc 或 loc 对多列进行过滤

Python中提取每个组/ID所属特定列中的自然数

Pandas 转换为日期时间

过滤阈值大小数据以使用 Pyspark 或 Python 读取

Python ** 用于负数

如何将虚拟变量列转换为多列?

python tkInter 浏览文件夹按钮

两个字符串之间的正则表达式匹配?

numpy.ndarray 与 pandas.DataFrame

使用逗号时,除了处理程序中的语法无效

如何使 Python3 成为 Geany 中的默认 Python

使用 pytest.fixture 返回模拟对象的正确方法

为什么`multiprocessing.Queue.get`这么慢?

是否在未完成初始化的对象上调用了 del?