Share five methods to simulate enum enumeration in Python

Source: Internet
Author: User
This article mainly introduces five methods to simulate the enum enumeration type in Python. This article provides the implementation code directly, you can refer to the following methods to simulate enum: (I think the method is simple and practical)

The code is as follows:


# Way1
Class Directions ctions:
Up = 0
Down = 1
Left = 2
Right = 3

Print Directions. down

# Way2
DirUp, dirDown, dirLeft, dirRight = range (4)

Print dirDown

# Way3
Import collections
Dircoll = collecoll. namedtuple ('direction', ('up', 'drop', 'left', 'right '))
Directions = dircoll (0, 1, 2, 3)

Print directions. DOWN

# Way4
Def enum (args, start = 0 ):
Class Enum (object ):
_ Slots _ = args. split ()

Def _ init _ (self ):
For I, key in enumerate (Enum. _ slots __, start ):
Setattr (self, key, I)

Return Enum ()

E_dir = enum ('up down left right ')

Print e_dir.down

# Way5
# Some times we need use enum value as string
Ctions = {'Up': 'up', 'Down': 'low', 'left': 'left', 'right': 'right '}

Print Directions ['low']

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.