Home >Backend Development >Python Tutorial >How Can C# Developers Represent Enums in Python?
Question:
As a C# developer working on a Python project, how can you represent the equivalent of an Enum in Python?
Answer:
Enumerations (Enums) have been introduced in Python 3.4 as part of PEP 435. They have also been backported to previous versions via third-party libraries like enum34 and aenum.
Using the enum Module (Python 3.4 ):
from enum import Enum Animal = Enum('Animal', 'ant bee cat dog')
This creates an Animal Enum with members ant, bee, cat, and dog.
Using enum34 Library (Python 2.7 ):
from enum34 import Enum Animal = Enum('Animal', 'ant bee cat dog')
Using aenum Library (Python 2.7 , 3.3 ):
from aenum import Enum class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4
Earlier Technique for Python Pre-3.4:
In earlier versions of Python, you can use a custom enum() function to create your own enums:
def enum(**enums): return type('Enum', (), enums) Numbers = enum(ONE=1, TWO=2, THREE='three')
Additional Techniques:
The above is the detailed content of How Can C# Developers Represent Enums in Python?. For more information, please follow other related articles on the PHP Chinese website!