在没有类名的情况下获取Python中的枚举名 [英] Get enum name in Python without class name
本文介绍了在没有类名的情况下获取Python中的枚举名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建自己的枚举。这将有名称,但没有值。
调用此枚举时,应始终返回名称。
I would like to create my own enum. This will have names but no values. When calling this enum it should always return the name.
from enum import Enum
class myEnum(Enum):
def __repr__(self):
return self.name
my_enum = myEnum('enum', ['a', 'b'])
使用:
print(my_enum.a)
它将返回a。没关系。
但是在一个类中使用它:
But using this in a class:
class T():
def do_something(self):
print(my_enum.a)
使用:
T().do_something()
将返回枚举。a
目标是始终返回a。
推荐答案
如果调用此枚举时,它应始终返回名称,表示字符串$ c的含义$ c>是必需的,然后可以将此方法添加到
myEnum
类中:
If When calling this enum it should always return the name means when a string
is required then you can add this method to the myEnum
class:
def __str__(self):
return self.name
这篇关于在没有类名的情况下获取Python中的枚举名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文