Search code examples
pythonobjectmethodsgetattr

__getattr__ equivalent for methods


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


Solution

  • 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