Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 - Convert enum to different datatypes

I'm currently working with an enum of the following type:

class System(Enum):
  FIRST = 1
  SECOND = 2

Now I'd like to be able to do the following:

a = System.FIRST
url = a.getSystemURL()

where the url for the enumeration members FIRST and SECOND are different of course.

I could create a dictionary with the enumeration members as keys and the urls as values, but this won't assure that if I later add an enumeration member I'll remember to add corresponding the dictionary entry.

Is there a clean way to have an enumeration with multiple values for the enumeration members? And to name these different values?

Something like this:

class System(Enum):
  Values = (Value, url, something)
  FIRST = 1, 'https://www.example.com', 42
  SECOND = 2, 'https://www.test.com', 13
like image 490
user9115052 Avatar asked Nov 18 '25 20:11

user9115052


1 Answers

There is an example like this in the documentation. If the class defines an __init__ method, the enum values will be passed to it as arguments. This means you can define your enum like so:

class System(Enum):
    FIRST = 1, 'https://www.example.com', 42
    SECOND = 2, 'https://www.test.com', 13

    def __init__(self, value, url, something):
        self.value_ = value
        self.url = url
        self.something = something

(Note that value is a special attribute reserved by enums, so I named the attribute value_ to avoid a name clash.)

You can now access these attributes on each enum member:

>>> System.FIRST.url
'https://www.example.com'
like image 187
Aran-Fey Avatar answered Nov 21 '25 10:11

Aran-Fey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!