美文网首页
python类比java动态代理

python类比java动态代理

作者: 木木_bfe8 | 来源:发表于2018-06-02 11:59 被阅读0次

    抄的

    class Proxy(object):
    
        def __init__(self, target):
            self.target = target
    
        def __getattribute__(self, name):
            target = object.__getattribute__(self, "target")
            '''获取Proxy中属性target,是RealHello实例'''
            print(target)
            attr = object.__getattribute__(target, name)
            print(name)
            '''获取RealHello实例的prints方法'''
            print(attr)
    
            def newAttr(*args, **kwargs):  # 包装
                print ("before print")
                res = attr(*args, **kwargs)
                print ("after print")
                return res
            return newAttr
    
    
    class RealHello(object):
    
        def prints(self, s):
            print ('hello', s)
    
    
    if __name__ == '__main__':
        t = RealHello()
        p = Proxy(t)
        p.prints("world")
    

    相关文章

      网友评论

          本文标题:python类比java动态代理

          本文链接:https://www.haomeiwen.com/subject/accrsftx.html