元类就是类的类
类可以用class创建,也可以用type创建:
class Foo:
pass
def __init__(self,name):
self.name = name
FFO = type('Foo',(object,),{'k':1,'__init__':__init__})
print(FFO.__dict__)
输出:
{‘k’: 1, ‘init’: <function init at 0x00000094FCF5C268>, ‘module’: ‘main’, ‘dict’: <attribute ‘dict’ of ‘Foo’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘Foo’ objects>, ‘doc’: None}
自定义元类
class MyType(type):
def __call__(self, *args, **kwargs): #传入参数self就是Foo,可变参数就是'alex'
obj = object.__new__(self) #传入Foo创建实例f1
self.__init__(obj,*args, **kwargs) #调用Foo.__init(f1,name)
return obj #返回实例对象
class Foo(metaclass=MyType): #Foo = MyType(Foo,'Foo',(父类),{属性字典},传给MyType的__init__
def __init__(self,name):
self.name = name
f1 = Foo('alex') #使用()本质上是调用Foo的__call__
print(f1.__dict__)
输出:
{‘name’: ‘alex’}