优点:特别添加了对属性的的操作。。
缺点:不支持使用魔法方法。
# 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)
网友评论