Python 面向对象高级编程 02 枚举类、元类

1 枚举类

from enum import Enum

# Month类型的枚举类
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr'))

for name, member in Month._member_map_.items():
    print(name, '=>', member, ',', member.value)

# for循环结果
Jan => Month.Jan , 1
Feb => Month.Feb , 2
Mar => Month.Mar , 3
Apr => Month.Apr , 4

# 更精确地控制枚举类型,从Enum派生出自定义类
from enum import Enum,unique
@unique # 帮助检查保证没有重复值
class Weekday(Enum):
    sun=0
    mon=1
    tue=2
    wed=3
    thu=4
    fri=5
    sat=6

# 访问枚举类型
day1=Weekday.mon
print(day1) # Weekday.mon

print(day1.value) # 1

print(Weekday(1)) # Weekday.mon

for name,member in Weekday.__members__.items():
    print(name,'=>',member)

# for循环结果
sun => Weekday.sun
mon => Weekday.mon
tue => Weekday.tue
wed => Weekday.wed
thu => Weekday.thu
fri => Weekday.fri
sat => Weekday.sat

2 元类

type() 函数既可以返回一个对象的类型,又可以创建出新的类型。

示例:

# 先定义函数
def fn(self,name='world'):
    print('hello, %s' %name)
# 创建Hello类
Hello=type('Hello',(object,),dict(hello=fn))

h=Hello()
h.hello() # hello, world

创建一个class对象,type() 函数要依次传入3个参数:

  1. class的名称
  2. 继承的父类集合,使用tuple写法
  3. class的方法名与函数绑定

注意:正常情况下,使用class … 来定义类,type()函数允许动态创建类。

2.1 metaclass

基本用不到,先省略不看

猜你喜欢

转载自blog.csdn.net/lihaogn/article/details/81262886
今日推荐