def with_metaclass(meta, *bases):
class metaclass(type):
print('enter mataclass')
def __new__(metacls, name, this_bases, d):
"""
修改了{name}类的父类
"""
print('[metaclass new]', metacls, name, this_bases, d)
return meta(name, bases, d)
def __init__(cls, *args, **kwargs):
print('[metaclass init]', cls, args, kwargs)
return type.__new__(metaclass, "temporary_class", (), {"x": lambda s: print(s)})
class A:
@staticmethod
def echo(s=None):
print(s)
class B(type):
def __init__(cls, *args, **kwargs):
"""
不会执行metaclass构造方法
"""
print('[B init]', cls, args, kwargs)
M = with_metaclass(B, A) # 创建的临时类
print('创建M的元类 ', M.__class__)
print('M的父类 ', M.__mro__)
print('>' * 20)
class N(M): # 创建类N时候才去执行metaclass中的方法
pass
print('创建N的元类 ', N.__class__)
print('N的父类 ', N.__mro__)
网友评论