gpt4 book ai didi

python - 为我的程序在 Python 中将 int 转换为枚举?

转载 作者:太空狗 更新时间:2023-10-30 01:58:11 24 4
gpt4 key购买 nike

如何在 python 中将 int 转换为 enum

最佳答案

如果你想在 int 和枚举之间灵活转换,你可以使用 enum.IntEnum

import enum

class Color(enum.IntEnum):
green = 1
blue = 2
red = 3
yellow = 4

color_code = 4
# cast to enum
color = Color(color_code)

# cast back to int
color_code = int(color)

注意:如果您使用的是 python<3.4,enum 已向后移植,但您需要安装它,例如通过 pip install enum

更多关于 python 中的枚举 - https://docs.python.org/3/library/enum.html

关于python - 为我的程序在 Python 中将 int 转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32041448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com