开发者

__getattr__ equivalent for methods

开发者 https://www.devze.com 2023-01-18 20:27 出处:网络
When an attribute is not found object.__getattr__ is called. Is there an eq开发者_开发百科uivalent way to intercept undefined methods?There is no difference. A method is also an attribute. (If you wan

When an attribute is not found object.__getattr__ is called. Is there an eq开发者_开发百科uivalent way to intercept undefined methods?


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


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


you didn't return anything.

class A(object):

  def __getattr__(self, attr):
    return attr

should work

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号