Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
5 views
in Python by (210 points)
Can anyone tell me how I can represent the equivalent of an Enum in Python?

2 Answers

+2 votes
by (10.9k points)
edited by

@Chandini , Enum was added to Python 3.4 and more advanced technques can be used using aenum library.To use aenum ,run $ pip install aenum.

Ex-

For new versions,

from enum import Enum     

Stationary = Enum('Stationary', 'pen pencil eraser ink')

Stationary.pen   #returns <Stationary.pen:1>

Stationary['pen'] #returns<Stationary.pen : 1>

Stationart.pen.name #returns ‘pen’

For earlier versions:

def enum(**enums):

return type('Enum', (), enums)

Example-

>>> Num = enum(ZERO='zero',ONE=1, TWO='two')

>>>Num.ZERO

'zero'

>>> Num.ONE

1

>>> Num.TWO

'two'

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

0 votes
by (106k points)

Here is one implementation:

class Enum(set):

    def __getattr__(self, name):

        if name in self:

            return name

        raise AttributeError

Here is its usage:

Animals = Enum(["ABC", "DAT", "HOP"])

print(Animals.ABC)

You can use the following video tutorials to clear all your doubts:-

Related questions

Browse Categories

...