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.
To get an enum name by value, pass the value to the enumeration class and access the name attribute, e.g. Sizes(1). name . When the value is passed to the class, we get access to corresponding enum member, on which we can access the name attribute.
The __str__() method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object. Now you can get the value of the enum directly, without accessing the value attribute on the enum member. You can also use square brackets to access enum members.
An Enum is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful repr() , grouping, type-safety, and a few other features. As you can see, creating an Enum is as simple as writing a class that inherits from Enum itself.
auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.
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
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