本文共 1513 字,大约阅读时间需要 5 分钟。
# -*- encoding: utf-8 -*-import functoolsimport time'''9、 第5章_元类关键:1 元类Python中的类也时对象。几乎所有都是对象。作为对象的类本身也是另一种类的实例,用于创建类。元类: 用于生成其他类的类就是元类。2 类与对象定义类时,仅仅是使用一个特殊的替代语法来代替不同类的实例化,即实例化type类。2.1 直接使用typetype构造函数接受3个参数:name: 类名bases:该类的基类元组attrs:该类的属性字典2.2 type链将一个对象传递给type,会返回该对象的类type类是基类,位于链的顶端,因此type(type)返回其自身2.3 type的角色type是其他元类的基类,其他类可以引用type作为其元类3 编写元类必须继承自type类3.1 __new__方法元类必须要定义__new__方法,该方法用于处理类的创建,且必须返回一个新类。__new__是一个类方法。参数:cls:元类自身name: 类名称bases: 类继承基类的元组attrs: 类应该包含的属性的字典3.2 元类继承元类可以继承3.3 直接用type创建类参数: 类名,父类元组,属性字典Animal = type( 'Animal', (object,), { '__init__': init, 'eat': eat, 'go_to_vet': go_to_vet, })参考:Python高级编程'''def init(self, name): self.name = namedef eat(self): passdef go_to_vet(self): pass'''用type来创建类'''Animal = type( 'Animal', (object,), { '__init__': init, 'eat': eat, 'go_to_vet': go_to_vet, })def meow(self): return Nonedef purr(self): return NoneCat = type( 'Cat', (Animal,), { 'meow': meow, 'purr': purr, })def useType(): homeCat = Cat(name='JiaFeiMao') print type(homeCat) print type(Cat) print type(type) print type(1)class MyMeta(type): def __new__(cls, name, bases, attrs): return super(MyMeta, cls).__new__(cls, name, bases, attrs)def useMetaClass(): # 创建一个类C C = MyMeta('C', (object,), {}) print type(C) class D(C): pass print type(D)def process(): useType() useMetaClass()if __name__ == "__main__": process()
转载地址:http://pvlfn.baihongyu.com/