美文网首页
python 动态代理模式 最佳模板

python 动态代理模式 最佳模板

作者: 假程序员 | 来源:发表于2020-07-01 20:18 被阅读0次

优点:特别添加了对属性的的操作。。
缺点:不支持使用魔法方法。

# coding=utf-8
class NativeProxy(object):
    def __init__(self, target):
        object.__setattr__(self, "_target", target)

    def __getattribute__(self, item):
        """修改get逻辑"""
        try:
            target = object.__getattribute__(self, item)
            if isinstance(target, type(object().__str__)):  # wrapped method
                raise AttributeError
            else:
                return target
        except AttributeError:
            target = object.__getattribute__(self, "_target")
            return getattr(target, item)

    def __setattr__(self, key, value):
        """修改set逻辑"""
        target = object.__getattribute__(self, "_target")
        if key in dir(target):
            setattr(target, key, value)
        else:
            object.__setattr__(self, key, value)


class A(object):
    _name = None

    def test(self):
        return "test"

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value


if __name__ == '__main__':
    a = A()
    p = NativeProxy(a)
    print(a.test())
    print(p.test())

    print(a.name)
    print(p.name)

    a.name = "a"
    print(a.name)
    print(p.name)

    p.name = "p"
    print(a.name)
    print(p.name)



相关文章

网友评论

      本文标题:python 动态代理模式 最佳模板

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