码迷,mamicode.com
首页 > 其他好文 > 详细

第一篇随笔

时间:2018-09-08 17:59:36      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:ret   self   closed   type   return   war   创建   lap   metaclass   

技术分享图片
 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‘)
元类的用法

 

第一篇随笔

标签:ret   self   closed   type   return   war   创建   lap   metaclass   

原文地址:https://www.cnblogs.com/Oliver-Lee/p/9609853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!