python—在pyhon中调用枚举类时如何动态替换变量

xmjla07d  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(420)

让我们举个例子。

class Animal(enum.Enum):
    dog = 1
    cat = 2
    lion = 3

# printing enum member as string

print ("The string representation of enum member is : ", Animal.dog)

上面的代码工作得很好。
现在我希望能够做到以下几点

ani = "dog"

# printing enum member as string

print ("The string representation of enum member is : ", Animal.ani)

上面的代码不起作用。如何实现上面的功能,在这里我可以动态地用变量替换

xggvc2p6

xggvc2p61#

使用名称查找功能:

print ("The string representation of enum member is : ", Animal[ani])

相关问题