__getattr__相当于方法

hoj*_*oju 5 python methods object getattr

找不到属性时object.__getattr__调用.是否存在拦截未定义方法的等效方法?

Ara*_*ion 10

没有区别.方法也是属性.(但是,如果您希望该方法具有隐式"自"参数,则必须执行更多工作来"绑定"该方法).


det*_*tly 8

方法也是属性.__getattr__对他们来说也是一样的:

class A(object):

  def __getattr__(self, attr):
    print attr
Run Code Online (Sandbox Code Playgroud)

然后尝试:

>>> 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
Run Code Online (Sandbox Code Playgroud)