Python enumeration class

Source: Internet
Author: User

This article mainly introduces the use of enumeration classes in Python, for more information, see: Python Learning Guide

When we need to define constants, one way is to use uppercase variables to define them by integers, such as the month:

=1=2=3=11=12

The advantage is simple, OK is the type is int , and still is the variable.

A better approach is to define a class type for such an enumeration type, and then each constant is a unique instance of class. Python provides the Enum ability to implement this feature:

fromimport= Enum('Month', ('Jan''Feb''Mar''Apr''May''Jun''Jul''Aug''Sep''Oct''Nov''Dec'))

This gives us the Month enumeration value of the type, which can be used directly Month.Jan to reference a constant, or to enumerate all its members:

forin Month.__members__.items():    print'=>'',', member.value)

valueproperty is automatically assigned to a member int constant, which is counted by default from the 1 start.

If you need to control the enumeration type more precisely, you can Enum derive the custom class from:

@uniqueclass Weekday(Enum):    =0    =1    =2    =3    =4    =5    =6

@uniqueAdorners can help us check that there are no duplicate values

There are several ways to access these enumeration types:

>>>Day1=Weekday.mon>>> Print(Day1) Weekday.mon>>> Print(Weekday.tue) Weekday.tue>>> Print(weekday[' Tue '].name) Tue>>> Print(Weekday.Tue.value)2>>> Print(Day1==Weekday.mon)True>>> Print(Day1==Weekday.tue)False>>> Print(Weekday (1)) Weekday.mon>>> Print(Day1==Weekday (1))True>>>Weekday (7Traceback (most recent): ...ValueError:7  is  notA valid Weekday>>>  forName, memberinchWeekday.__members__.items (): ...Print(Name,' = ', member) ... Sun=Weekday.sunmon=Weekday.montue=Weekday.tuewed=Weekday.wedthu=Weekday.thufri=Weekday.frisat=Weekday.sat

Python enumeration class

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.