python metaclass

有一篇很好的讲解 

http://blog.jobbole.com/21351/   

我所写的方便自己学习的例子。

#coding:utf8

class Application(object):
    def __init__(self):
        super(Application, self).__init__()
        self.items = {'key1':'value1','key3':'value3','key2':'value2'}
        
    def init_model(self,model_cls):
        for attr in self.items:
            setattr(model_cls, attr, self.items[attr])

app = Application()


class A(type):
    def __init__(self,name, bases, attrs):
        super(A, self).__init__(name, bases, attrs)
        app.init_model(self)
        setattr(self, "aa", self.aa)
        self._get_def_attrs()
    def aa(self):
        print 'aa'
    def _get_def_attrs(self):
        if not hasattr(self, "key4"):
            setattr(self,'key4','value4')


class B(object):
    __metaclass__ = A
    def __init__(self):
        super(B,self).__init__()
    def xx(self):
        print 'xx'

class C(B):
    def __init__(self):
        super(C, self).__init__()
        self.need_insert = True
    def cc(self):
        print 'cc'

 

posted on 2013-06-21 10:29  tiger4py  阅读(180)  评论(0)    收藏  举报

导航