• python 枚举类


    枚举类

    Enum类

    from enum import Enum

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

    value属性则是自动赋给成员的int常量,默认从1开始计数
    for name, member in Month.__members__.items():
    print(name, '=>', member, ',', member.value)


    自定义类
    from enum import Enum, unique

    @unique
    class Weekday(Enum):
    Sun = 0 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6
    @unique装饰器可以帮助我们检查保证没有重复值
    访问:
    >>> print(Weekday['Tue'])
    Weekday.Tue
    >>> print(Weekday.Tue.value)
    2
    >>> print(Weekday(1))
    Weekday.Mon

     

    朝闻道
  • 相关阅读:
    053-146
    053-659
    053-658
    053-657
    053-656
    053-654
    053-655
    053-652
    053-651
    053-650
  • 原文地址:https://www.cnblogs.com/wander-clouds/p/8460962.html
Copyright © 2020-2023  润新知