python 动态代理模式 最佳模板
2020-07-01 本文已影响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)