#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Pw @ 2017-05-15 10:04:20
class Proxy:
def __init__(self, obj):
self._obj = obj
def __getattr__(self, name):
print('getattr:', name)
return getattr(self._obj, name)
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value)
else:
print('setattr:', name, value)
setattr(self._obj, name, value)
def __delattr__(self, name):
if name.startswith('_'):
super().__delattr__(name)
else:
print('delattr:', name)
delattr(self._obj, name)
class Spam:
def __init__(self, x):
self.x = x
def bar(self, y):
print('Spam.bar', self.x, y)
s = Spam(2)
p = Proxy(s)
print(p.x)
print(p.bar(3))
p.x = 37
print(p.x)
```
作用: 通过自定义属性访问方法,你可以用不同方式自定义代理类行为 (比如加入日志功
能、只读访问等)。