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")
View Code

 

 

代码执行结果如下:

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  阅读(23)  评论(0编辑  收藏  举报

导航