Get enum name in Python without class name

北战南征 提交于 2020-07-09 04:04:13

问题


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'])

With:

print(my_enum.a) 

it will returns a. That's ok.

But using this in a class:

class T():
    def do_something(self):
        print(my_enum.a)

With:

T().do_something()

will return enum.a

Goal is this will always return a.


回答1:


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


来源:https://stackoverflow.com/questions/53297848/get-enum-name-in-python-without-class-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!