擅长:python、mysql、java
<p><code>__getattr__()</code>是可以定义的特殊方法函数。当成员查找失败时,将调用此函数。</p>
<p><code>getattr()</code>是一个可以调用以尝试成员查找的函数。如果查找成功,则获取成员(可能是方法函数对象,也可能是数据属性对象)。<code>getattr()</code>在查找失败的情况下也可以返回默认值。</p>
<p>如果您声明一个<code>__getattr__()</code>成员函数,您可以使它有时成功,也可以使它每次成功。</p>
<pre><code>class A(object):
def __getattr__(self, name):
return "I pretend I have an attribute called '%s'" % name
a = A()
print a.foo # prints "I pretend I have an attribute called 'foo'"
</code></pre>
<p>Python还有一个<code>__getattribute__()</code>在每次查找时都会调用它。这是非常危险的,因为它可能使它无法正常访问成员。</p>
<pre><code>class A(object):
def __init__(self, value):
self.v = value
def __getattribute__(self, name):
return "I pretend I have an attribute called '%s'" % name
a = A(42)
print a.v # prints "I pretend I have an attribute called 'v'"
print a.__dict__["v"] # prints "I pretend I have an attribute called '__dict__'"
</code></pre>
<p>哎呀,现在不可能访问a.v!</p>