方法的等价物 __getattr__

17

当属性未找到时,会调用object.__getattr__。是否有一种类似的方法来拦截未定义的方法?

3个回答

12

没有区别。方法也是属性。(如果你想让这个方法有一个隐式的"self"参数,那么你需要做一些额外的工作来"绑定"这个方法)。


同意,所有的东西都是对象,无论它是 intstr 还是 function - Tomasz Zieliński

10

方法也是属性,__getattr__对它们也适用:

class A(object):

  def __getattr__(self, attr):
    print attr

然后尝试:

>>> a = A()
>>> a.thing
thing
>>> a.thing()
thing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

0

你没有返回任何东西。

class A(object):

  def __getattr__(self, attr):
    return attr

应该可以工作

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接