__getattr__ equivalent for methods

那年仲夏 提交于 2019-12-23 11:54:15

问题


When an attribute is not found object.__getattr__ is called. Is there an equivalent way to intercept undefined methods?


回答1:


Methods are attributes too. __getattr__ works the same for them:

class A(object):

  def __getattr__(self, attr):
    print attr

Then try:

>>> 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



回答2:


There is no difference. A method is also an attribute. (If you want the method to have an implicit "self" argument, though, you'll have to do some more work to "bind" the method).




回答3:


you didn't return anything.

class A(object):

  def __getattr__(self, attr):
    return attr

should work



来源:https://stackoverflow.com/questions/3855015/getattr-equivalent-for-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!