元类作用时机
当使用此元类定义新类时(如 class MyClass(metaclass=StaticMethodMeta)),元类的 __new__ 方法会在类创建时被调用。
利用元类改变类特性 -> 创建一个成员函数自动转换为静态成员函数的类
</>
python
1class StaticMethodMeta(type):
2 def __new__(cls, name, bases, namespace):
3 for attr_name, attr_value in namespace.items():
4 if callable(attr_value) and not attr_name.startswith('__'):
5 namespace[attr_name] = staticmethod(attr_value)
6 return super().__new__(cls, name, bases, namespace)
7
8class tool(metaclass=StaticMethodMeta):
9 # 静态成员没有self参数
10 def tool1(p1, p2):
11 pass