Python 元类
Python 元类(metaclass)
对象
Python 中一切皆对象,连类也不例外。
对象中包含三个关键性属性:
- 标识 使用
id()方法查看 - 对象值
- 类型 使用
type()方法查看
类与对象
Python 中使用 class 关键字定义类,通过定义的类生成类实例。实例称之为实例对象。Python 中类是一个对象,所有内建类型的类型都是 type,这个 type 就是元类,元类就是 Python 中的造物主。
道生一,一生二,二生三,三生万物。
道 即是 type
一 即是 metaclass(元类,或者叫类生成器)
二 即是 class(类,或者叫实例生成器)
三 即是 instance(实例)
万物 即是 实例的各种属性与方法,我们平常使用python时,调用的就是它们。
| |
现在我们都知道类(对象)可以使用 class 关键字创建,我们还知道类(对象)的类型是 type,既然知道了它的类型是 type,那么肯定可以通过 type(元类)来创建。
类的创建过程
- 确定类的父类是否包含 metaclass 参数,没有就执行下一步
- 确定类的父类的父类是否包含 metaclass 参数,没有就执行下一步
- 使用默认元类 type
定义元类
函数方式
| |
类方式
| |
元类的应用
- ORM
- 限定子类行为
- 注册所有子类
实例化过程
实例:__call__ »> __new__ »> __init__ »> instance
类实例:__prepare__ »> __call__ »> __new__ »> __init__ »> class instance
特殊函数签名
| |
元类 super 方法
| |
x = Foo() == type(Foo).__call__(Foo)
元类中的 super() == super(Singleton, cls) 方法调用了待实例化的类 __new__ and __init__
super(cls, instance)(isinstance(instance, cls) must be True), the method is selected from the next class ininstance.__class__.__mro__starting frominstance.__class__.super(cls0, cls1)(issubclass(cls1, cls0) must be True), the method is selected from next class incls1.__mro__starting from cls0