26 Using enum Classes

Source: Internet
Author: User

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

12 3

The advantage is simple, the disadvantage is that the type is int , and is still a 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 Enum classes to implement this functionality:

 from enumImport Enummonth= Enum ('Month', ('Jan','Feb','Mar','APR',' May','June','Jul',' the','Sep','Oct','Nov','Dec'))

valueproperty is a constant that is automatically assigned to a member int , and is counted from the beginning by default 1 .

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

 from enum import Enum, Unique@unique class Weekday (Enum):     0 # Sun's value is set to 0     1      2345             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']) Weekday.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  isNot a valid Weekday>>> forName, memberinchweekday.__members__.items (): .... Print (name,'=', member) ... Sun=Weekday.sunmon=Weekday.montue=weekday.tuewed=Weekday.wedthu=Weekday.thufri=Weekday.frisat= Weekday.sat

Visible, you can either reference the enumeration constant with the member name, or you can get the enumeration constant directly based on the value.

Summary

EnumA set of related constants can be defined in a class, and the class is immutable, and members can be compared directly.

26 Using enum Classes

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.