gpt4 book ai didi

python - 如何在Python中通过动态传递 'value'来获取 'enum member name'?

转载 作者:行者123 更新时间:2023-12-05 02:09:58 25 4
gpt4 key购买 nike

如何在Python中通过动态传递'枚举成员名称'来获取'值'?

例如考虑下面的枚举

import enum 
class Animal(enum.Enum):
DOG = "This is Dog"
CAT = "This is cat"
LION = "This is Lion"

我想写一个像下面这样的通用函数,它必须返回This is Dog

def get_enum_value("DOG"):
#
# SOME CODE HERE TO GET THE VALUE FOR THE GIVEN (METHOD ARGUMENT) ENUM PROPERTY NAME
#

最佳答案

简化和完整的代码:

## Enum definition
import enum
class Animal(enum.Enum):
DOG = "This is Dog"
CAT = "This is cat"
LION = "This is Lion"


## method to return enum value when pass the enum member name
def get_enum_member_value(enum_member_name):
enum_member_value = Animal[enum_member_name].value
return enum_member_value


## execute the method and print the value
print(get_enum_member_value("DOG"))

关于python - 如何在Python中通过动态传递 'value'来获取 'enum member name'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59300775/

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