Share the following five methods for simulating enum enumeration in Python: pythonenum

Source: Internet
Author: User

Share the following five methods for simulating enum enumeration in Python: pythonenum

The following methods are used to simulate enum: (sensory method 1 is simple and practical)

Copy codeThe 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.