<p>捕获未定义属性的标准方法是使用<code>__getattr__</code>:</p>
<pre><code># But see the end of the answer for an afterthought
def __getattr__(self, attr):
return self.sleep
</code></pre>
<p>Python不区分“常规”属性和方法;方法调用从普通属性查找开始,其结果恰好是可调用的。也就是说</p>
<pre><code>billy.run()
</code></pre>
<p>与相同</p>
<pre><code>f = billy.run
f()
</code></pre>
<p>这意味着<code>__getattr__</code>将为<em>任何</em>未定义的属性调用;在查找时无法判断是否要调用结果。你知道吗</p>
<hr/>
<p>但是,如果您只想为一个公共方法定义“别名”,那么可以在<code>class</code>语句之后使用循环来实现。你知道吗</p>
<pre><code>class Person:
def __init__(self): pass
def say(self, speech): pass
def walk(self, destination): pass
def jump(self): pass
def do_all(self): pass
for alias in ["something", "something_else", "other"]:
setattr(Person, alias, Person.do_all)
</code></pre>
<p>您也可以在</em>的<code>class</code>语句中进行硬编码赋值<em>,但是如果您提到的这种情况有数百种,那么这将是很难处理的:</p>
<pre><code>class Person:
def do_all(self): pass
something = do_all
something_else = do_all
</code></pre>
<p>(我没有尝试使用<code>exec</code>在循环中自动执行此类分配;这可能是可能的,但不建议这样做。)</p>
<p>您还可以将别名列表嵌入到<code>__getattr__</code>的定义中,想想看:</p>
<pre><code> def __getattr__(self, attr):
if attr in ["something", "something_else", "other"]:
return self.sleep
else:
raise AttributeError(f"type object 'Person' has no attribute '{attr}'")
</code></pre>