python,使用枚举类,面向对象高级编程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python,使用枚举类,面向对象高级编程相关的知识,希望对你有一定的参考价值。

python

#针对常量
#枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。

from enum import Enum

Month = Enum(Month, (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec))
#这样我们就获得了Month类型的枚举类

for name, member in Month.__members__.items():
    print(name, =>, member, ,, member.value)
#value属性则是自动赋给成员的int常量,默认从1开始计数。
如果需要更精确地控制枚举类型,可以从Enum派生出自定义类:
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装饰器可以帮助我们检查保证没有重复值。

#访问这些枚举类型可以有若干种方法:

day1 = Weekday.Mon
print(day1)Weekday.Mon
print(Weekday[Tue])   Weekday.Tue
print(Weekday.Tue.value)  2
print(Weekday(1))   Weekday.Mon
print(day1 == Weekday(1))True

for name, member in Weekday.__members__.items():
    print(name, =>, member)
#结果
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat

 

以上是关于python,使用枚举类,面向对象高级编程的主要内容,如果未能解决你的问题,请参考以下文章

python Class:面向对象高级编程 Enum(枚举)@unique

python 面向对象编程(高级篇)

python基础之面向对象高级编程

进击的Python第七章:Python的高级应用面向对象编程进阶

面向对象编程(python)和部分面向对象高级编程

Python面向对象高级编程(__slots__多继承定制类)-6