+1 vote
4 views
in Python by (220 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'

0 votes
by (107k 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:-

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...