Python tips 31[python using enum][]

Source: Internet
Author: User

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

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

Print Directions.down

# Way2
Dirup, Dirdown, dirleft, dirright = Range (4)

Print Dirdown

# WAY3
Import Collections
Dircoll=collections.namedtuple (' Directions ', (' Up ', ' off ', ' 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-left-right ')

Print E_dir.down

# Way5
# Some times we need use enum value as String
Directions = {' Up ': ' Up ', ' off ': ' Down ', ' left ': ' Left ', ' right ': ' Right '}

Print directions[' down ']

Problem: Sometimes it is necessary to use the value of enum as a string, as indicated in Way5, do you have a better way?

Reference: http://audbel.com/0/5009691

Http://www.cnblogs.com/itech/archive/2011/03/08/1977245.html

Python tips 31[python using enum][]

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.