一、创建类的执行流程
二、元类的认识
什么是元类呢?在Python3中继承type的就是元类
三、元类的示例
方式一:
1 # 方式一 2 class MyType(type): 3 '''继承type的就是元类''' 4 def __init__(self,*args,**kwargs): 5 print("MyType创建的对象",self) #Foo 6 super(MyType,self).__init__(*args,**kwargs) 7 8 def __call__(self, *args, **kwargs): 9 obj = super(MyType,self).__call__(*args,**kwargs) 10 print("类创建对象",self,obj) #Foo 11 12 class Foo(object,metaclass=MyType): # 对象加括号会去执行__call__方法,__call__方法里面继承了type的__call__方法 13 ,type的__call__方法里面会先执行__new__方法,再去执行__init__方法。 14 所以,Foo就是用type创建出来的 15 user = "haiyan" 16 age = 18 17 18 obj = Foo()
方式二
1 # 方式二 2 class MyType(type): 3 def __init__(self, *args, **kwargs): 4 print("ssss") 5 super(MyType, self).__init__(*args, **kwargs) 6 7 def __call__(cls, *args, **kwargs): 8 v = dir(cls) 9 obj = super(MyType, cls).__call__(*args, **kwargs) 10 return obj 11 #对象加括号就会去执行__call__方法 12 class Foo(MyType('Zcc', (object,), {})): #MyType('Zcc', (object,), {})相当于class Zcc(object):pass,也就是创建了一个Zcc的类 13 user = 'haiyan' 14 age = 18 15 16 obj = Foo()
方式三
1 # 方式三 2 class MyType(type): 3 def __init__(self, *args, **kwargs): 4 print("ssss") 5 super(MyType, self).__init__(*args, **kwargs) 6 7 def __call__(cls, *args, **kwargs): 8 v = dir(cls) 9 obj = super(MyType, cls).__call__(*args, **kwargs) 10 return obj 11 #对象加括号就会去执行__call__方法 12 13 def with_metaclass(arg,base): 14 print("类对象",MyType('Zcc', (base,), {})) 15 return arg('Zcc', (base,), {}) #返回一个类对象 <class '__main__.Zcc'> 16 17 class Foo(with_metaclass(MyType,object)): #MyType('Zcc', (object,), {})相当于class Zcc(object):pass,也就是创建了一个Zcc的类 18 user = 'haiyan' 19 age = 18 20 21 obj = Foo()
=======================附加===========================
1 class ASD(type): 2 pass 3 4 qqq = ASD("qwe", (object,), {}) #用ASD这个元类创建了一个(qwe,并且继承object类的)类 5 6 # class ASD(qwe): 7 # pass 8 obj = qqq() 9 # 能创建类的是元类 10 # 能创建对象的是类 11 print(obj) #<__main__.qwe object at 0x00000000024FFBA8> 12 print(obj.__class__) #<class '__main__.qwe'> 13 print(obj.__class__.__class__) #<class '__main__.ASD'> 14 print(obj.__class__.__class__.__class__) #<class 'type'> 15 print(obj.__class__.__class__.__class__.__class__) #<class 'type'>
归类: flask