python - metaclass

metaclass 的作用
- 在python 的世界, 一起都是object. 類也是object。 上面這張圖很好的描述了class 類的創建過程。 通過下面的例子來了解類的創建過程, 實例對象的創建過程。
通過這個過程, 可以了解metaclass 的作用。
1 import re 2 3 4 class LittleMeta(type): 5 def __new__(cls, clsname, superclasses, attributedict): 6 if re.match("[a-z]", clsname[0]): 7 raise Exception 8 print(f"LittleMeta __new__ - attributedict {attributedict}。。。") 9 return type.__new__(cls, clsname, superclasses, attributedict) 10 11 def __init__(self, *args, **kwargs): 12 print(f"LittleMeta __init__ *args - {args}... **kwargs - {kwargs}...") 13 pass 14 15 def __call__(self, *args, **kwargs): 16 print("LittleMeta __call__ *args - {args}... **kwargs - {kwargs}...") 17 super(LittleMeta, self).__call__(*args, **kwargs) 18 19 20 class Student(metaclass=LittleMeta): 21 cls_name = "jiangnan" 22 def __init__(self, name, age): 23 self.name = name 24 self.age = age 25 26 27 28 print("start assign a instance for Student class") 29 s1 = Student("allen", 15) 30 print("done")
代碼執行結果如下:
LittleMeta __new__ - attributedict {'__module__': '__main__', '__qualname__': 'Student', 'cls_name': 'jiangnan', '__init__': <function Student.__init__ at 0x000001FC22235A20>}。。。
LittleMeta __init__ *args - ('Student', (), {'__module__': '__main__', '__qualname__': 'Student', 'cls_name': 'jiangnan', '__init__': <function Student.__init__ at 0x000001FC22235A20>})... **kwargs - {}...
start assign a instance for Student class
LittleMeta __call__ *args - {args}... **kwargs - {kwargs}...
done
分析:
1. 在創建Student class 的過程中, 即 line 20 class Student, python 其實是實例化metaclass, 調用的metaclass 的 __new__(), __init__()
2. 在執行 s1 = Student("allen", 15) 時, 其實是調用metaclass 的__call__().
posted on 2022-11-24 14:48 MissLi12138 閱讀(42) 評論(0) 收藏 舉報
浙公網安備 33010602011771號