测试代码如下:
1 class ModelMetaClass(type): 2 def __new__(cls,name,base,attrs): 3 logging.info("cls is:"+str(cls)) 4 logging.info("name is:"+str(name)) 5 logging.info("base is:"+str(base)) 6 logging.info("attrs is:"+str(attrs)) 7 return type.__new__(cls,name,base,attrs) 8 pass 9 pass 10 11 class Model(dict): 12 __metaclass__ = ModelMetaClass 13 def __init__(self): 14 pass 15 pass 16 17 def main(): 18 m=Model() 19 20 if __name__ == '__main__': 21 main()
测试结果:
1 INFO:root:cls is:<class '__main__.ModelMetaClass'> 2 INFO:root:name is:Model 3 INFO:root:base is:(<type 'dict'>,) 4 INFO:root:attrs is:{'__module__': '__main__', '__metaclass__': <class '__main__.ModelMetaClass'>, '__init__': <function __init__ at 0x025C76F0>}
结论就显而易见了。cls是当前类的名字,即类本身。name是通过__metaclass__属性指向ModelMetaClass的类,即要实例化的类,ModelMetaClass拦截了该类的实例化。base是要实例化的类的基类。attrs是要实例化的类的属性集合。