__getattr__ equivalent for methods
Asked Answered
P

3

18

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

Priapic answered 4/10, 2010 at 12:2 Comment(0)
L
11

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
Letishaletitia answered 4/10, 2010 at 12:8 Comment(0)
B
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).

Brachycephalic answered 4/10, 2010 at 12:4 Comment(1)
Second that, everything is an object, no matter if it's int, str or function.Aerophyte
L
11

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
Letishaletitia answered 4/10, 2010 at 12:8 Comment(0)
F
0

you didn't return anything.

class A(object):

  def __getattr__(self, attr):
    return attr

should work

Fisher answered 6/4, 2013 at 4:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.