標籤:
測試代碼如下:
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 pass10 11 class Model(dict):12 __metaclass__ = ModelMetaClass13 def __init__(self):14 pass15 pass16 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:Model3 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是要執行個體化的類的屬性集合。
Python中type建構函式參數說明