MetaClass
它的作用主要是 指定由谁来创建类,默认是type
#python3 class Foo(metaclass=MyType): pass #python2 class Foo(object): __metaclass__ = MyType
注意下面的代码中的运行结果,如果某个基类执行谁来创建,那么继承这个基类的派生类也由这个谁来创建
class MyType(type): def __init__(self,*args,**kwargs): print('init') super(MyType, self).__init__(*args, **kwargs) def __call__(self, *args, **kwargs): print('call本质:调用类的__new__,在调用init方法') return super(MyType, self).__call__(*args, **kwargs) class Foo(metaclass=MyType): def __call__(self, *args, **kwargs): print('123') class Bar(Foo): pass Foo() #实例化对象,会执行负责创建类的type里的__call__方法 obj = Bar() obj() #对象+() 执行父类的里__call__方法
应该见过这样创建类的吧,通过type创建Base = type('Base', (object,), {})
所以我们通过继承type的自定义type类也是可以这么做的Base = MyType('Base', (object,), {}),那这个过程本质也就是和上面metaclass一样的效果,指定了MyType进行创建类
class MyType(type): def __init__(self, *args, **kwargs): super(MyType, self).__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): print('xxxx') return super(MyType, cls).__call__(*args, **kwargs) # Base = MyType('Base', (object,), {}) # MyType('Base', (object,), {}) 是有MyType创建; metaclass=MyType # 1. type可以创建类metaclass=type;MyType也可以创建类metaclass=MyType # 2. Base = MyType('Base', (object,), {}) --> # class Base(metaclass=MyType): # pass # class Foo(Base): # pass class Foo(MyType('Base', (object,), {})): pass obj = Foo()
所以这个Foo继承的是MyType创建的类,而Foo子类也会由MyType进行创建,似乎这种方式看起更简洁
不过把创建Base类型整个过程都写在Foo继承上,难免有些看着有些糟心,另外base执行继承类也是写死了,我们可独立出一个函数进行封装,并动态实现传入继承类
class MyType(type): def __init__(self, *args, **kwargs): super(MyType, self).__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): return super(MyType, cls).__call__(*args, **kwargs) def with_metaclass(base): return MyType('XX', (base,), {}) class Foo(with_metaclass(object)): pass