search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Custom type enumeration

But sometimes we need to control the type of enumeration, then we can derive a custom class from Enum to meet this need. By modifying the above example:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from enum import Enum, unique
Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
# @unique 装饰器可以帮助我们检查保证没有重复值
@unique
class Month(Enum):
    Jan = 'January'
    Feb = 'February'
    Mar = 'March'
    Apr = 'April'
    May = 'May'
    Jun = 'June'
    Jul = 'July'
    Aug = 'August'
    Sep = 'September '
    Oct = 'October'
    Nov = 'November'
    Dec = 'December'
if __name__ == '__main__':
    print(Month.Jan, '----------',
          Month.Jan.name, '----------', Month.Jan.value)
    for name, member in Month.__members__.items():
        print(name, '----------', member, '----------', member.value)

The output result is as follows:

7ee49a517fbabe7772b6f5c5b285ad0.png

Through the above example, you can know that the enumeration module defines an iterator (interator) and comparison (comparison) function enumeration type. It can be used to create well-defined symbols for values ​​instead of using concrete integers or strings.

new file
Reset Code
Automatic operation
submit
Preview Clear