Python enum get value | Example code

Use the value attribute in the enum if you want to get value in Python.

Python enum get value example

Simple example code has defined the enum and prints the value.

from enum import Enum


class D(Enum):
    x = 100
    y = 200


print(D.x.value)

Output:

Python enum get value

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation. It will also allow you to print it in that way also in lists.

from enum import Enum


class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2


print(D.x)

Output: 1

Do comment if you have any doubts and suggestions on this Python enum topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.