17

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

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
hoju
  • 28,392
  • 37
  • 134
  • 178

3 Answers3

12

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

Arafangion
  • 11,517
  • 1
  • 40
  • 72
10

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
detly
  • 29,332
  • 18
  • 93
  • 152
0

you didn't return anything.

class A(object):

  def __getattr__(self, attr):
    return attr

should work

Anthon
  • 69,918
  • 32
  • 186
  • 246
panpog
  • 11
  • 2