擅长:python、mysql、java
<p>有点优雅的解决方案是在包装类上创建一个“属性代理”:</p>
<pre><code>class Wrapper(object):
def __init__(self, wrappee):
self.wrappee = wrappee
def foo(self):
print 'foo'
def __getattr__(self, attr):
return getattr(self.wrappee, attr)
class Wrappee(object):
def bar(self):
print 'bar'
o2 = Wrappee()
o1 = Wrapper(o2)
o1.foo()
o1.bar()
</code></pre>
<p>所有的魔术都发生在<code>Wrapper</code>类的<code>__getattr__</code>方法上,该方法将尝试访问<code>Wrapper</code>实例上的方法或属性,如果它不存在,它将尝试使用包装的方法或属性。</p>
<p>如果试图访问两个类中都不存在的属性,则会得到以下结果:</p>
<pre><code>o2.not_valid
Traceback (most recent call last):
File "so.py", line 26, in <module>
o2.not_valid
File "so.py", line 15, in __getattr__
raise e
AttributeError: 'Wrappee' object has no attribute 'not_valid'
</code></pre>