首页 > 代码库 > python元类__metaclass__

python元类__metaclass__

<pre name="code" class="python">#python元类,类的创建过程
#首先调用type.__new__
#然后调用类的构造函数 class.__init__

def toString(c):
    s="";
    if type(c)==tuple:
        s="tuple:"
        for i in c:
            s+=str(i)
            s+=","
        return s
    elif type(c) == dict:
        s="dict:"
        for k,v in c.items():
            s+= "k=%s,v=%s" % (k,v)
            s+=","
        return s
    elif type(c) == list:
        s="list:"
        for i in c:
            s+=str(i)
            s+","
        return s
    else:
        return c
        

class ListMetaClass(type):
    def __new__(cls, name, bases, attr):
        #对于比较长的代码行,可以使用\来分行
        #有没有感觉跟C++的define定义换行的感觉一样(-><*><-)
        print('cls=%s, name=%s,bases=%s,attrs=%s'              % (toString(cls), toString(name),                  toString(bases), toString(attr)))
        attr['add']=lambda self,value:self.append(value)
        return type.__new__(cls, name, bases, attr)
    
class MyList(list):
    __metaclass__ = ListMetaClass
    
    
if __name__ == "__main__":
    myList = MyList()
    myList.add(100)
    print(myList)
    
    def listAdd(self,value):
        self.append(value)
        
    MyList2 = ListMetaClass("MyList2", (list,), dict(add=listAdd))
    myList2=MyList2()
    myList2.add(1000)
    print(myList2)
"""
程序输出:
cls=<class '__main__.ListMetaClass'>, 
name=MyList,
bases=tuple:<type 'list'>,,
attrs=dict:k=__module__,v=__main__,k=__metaclass__,v=<class '__main__.ListMetaClass'>,
[100]
cls=<class '__main__.ListMetaClass'>, 
name=MyList2,
bases=tuple:<type 'list'>,,
attrs=dict:k=add,v=<function listAdd at 0x01AACBB0>,
[1000]
"""    


python元类__metaclass__