http://www.cnblogs.com/linhaifeng/articles/8029564.html
元类:
一切源自于一句话:python中一切皆为对象。
class People: def __init__(self, name): self.name = name p = People("zhangsan") print(type(p)) # 查看p 对象的类:<class '__main__.People'> print(type(People)) # <class 'type'> type这个元类产生了People类,默认的元类type
如果一切皆为对象,那么类People本质也是一个对象,既然所有的对象都是调用类得到的,那么People必然也是调用了一个类得到的,这个类称为元类
定义类的另外一种方法
def func(self): print('func...') Foo = type('Foo',(object,),{'x':1,'func':func}) f1 = Foo() print(f1.x) f1.func()
自定义元类
class MyType: def __init__(self,a,b,c): print('元类构造函数执行...') print(a) # Foo print(b) # () print(c) # {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000026A4AEC5B70>} class Foo(metaclass=MyType): # MyType(Foo,'Foo',(),{}) def __init__(self): pass
class MyType(type): def __init__(self,a,b,c): print('元类构造函数执行...') def __call__(self, *args, **kwargs): obj = object.__new__(self) self.__init__(obj,*args, **kwargs) return obj class Foo(metaclass=MyType): # MyType(Foo,'Foo',(),{}) def __init__(self, name): self.name = name f1 = Foo("zhangsan") print(f1.__dict__) # {'name': 'zhangsan'}