1 #元类
2 class myType(type):
3 def __init__(self, obj_name, base_tuple, attr_dict):
4 print(self, obj_name, base_tuple, attr_dict, sep='\n')
5
6 def __call__(self, *args, **kwargs):
7 print(self, args, kwargs, sep='\n')
8 #<class '__main__.Foo'>
9 #('oliver',)
10 #{}
11 obj = object.__new__(self, *args, **kwargs)
12 self.__init__(obj, *args, **kwargs)
13 #调用self (在这里是Foo)的init方法 不是调用myType的init方法
14 return obj
15
16 def __new__(cls, *args, **kwargs):#生成一个类
17 print(cls, args, kwargs, sep='\n')
18 obj = type.__new__(cls, *args, **kwargs)
19 #print(obj)
20 return obj
21
22
23 class Foo(object, metaclass=myType): #元类默认为type 即Foo = type(Foo, 'Foo', (object,), {attr1:a,attr2:b})
24 #用元类创建时 调用的是myType的init方法
25 def __init__(self, name):
26 self.name = name
27
28 print(Foo)
29 #bar = Foo('oliver')
30 #print(bar, bar.__dict__, sep='\n')
元类的用法