Python中type的构造函数参数含义说明
测试代码如下:
classModelMetaClass(type): def__new__(cls,name,base,attrs): logging.info("clsis:"+str(cls)) logging.info("nameis:"+str(name)) logging.info("baseis:"+str(base)) logging.info("attrsis:"+str(attrs)) returntype.__new__(cls,name,base,attrs) pass pass classModel(dict): __metaclass__=ModelMetaClass def__init__(self): pass pass defmain(): m=Model() if__name__=='__main__': main()
测试结果:
INFO:root:clsis:<class'__main__.ModelMetaClass'> INFO:root:nameis:Model INFO:root:baseis:(<type'dict'>,) INFO:root:attrsis:{'__module__':'__main__','__metaclass__':<class'__main__.ModelMetaClass'>,'__init__':<function__init__at0x025C76F0>}
结论就显而易见了。cls是当前类的名字,即类本身。name是通过__metaclass__属性指向ModelMetaClass的类,即要实例化的类,ModelMetaClass拦截了该类的实例化。base是要实例化的类的基类。attrs是要实例化的类的属性集合。