I have an enum class in python using list of strings:
from enum import Enum
myEnum = Enum('myEnum',['typeA',typeB','typeC'])
and I want to add method "str" to this enum class:
def __str__(self):
return self.name
so that when I use str() function, I only get the 'typeX' part, i.e. the enum part withou class name. e.g.
print(str(myEnum.typeA)) # I want this to print "typeA" instead of "myEnum.typeA"
I do not know how to add the "str" method to this class as it is not class definition? Thanks for your help.
If this is something you do a lot, you can make your own base Enum class, and then use that in the function calls:
class MyBaseEnum(Enum):
def __str__(self):
return self.name
myEnum = MyBaseEnum('myEnum',['typeA','typeB','typeC'])
and in use:
>>> print(myEnum.typeB)
typeB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With