The default python behaviour when calling a class method that does not exist is that you get an exception:
But if you want a class that catchs all methods even methods that do not exist, you have to override the __getattribute__ method:
Here we have the __getattribute___ method will try to call the method you want to call, if it exists you will get it:
and if you try to call a method that does not exist, the catch_all method will be called:
>>> class A(object):
... pass
...
>>> a = A()
>>> a.getBlablabla()
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: 'A' object has no attribute 'getBlablabla'
But if you want a class that catchs all methods even methods that do not exist, you have to override the __getattribute__ method:
>>> class A(object):
... def __getattribute__(self,name):
... try:
... return object.__getattribute__(self, name)
... except AttributeError:
... return self.catch_all(name)
...
... def realmethod(self):
... print 'I am realmethod'
...
... def catch_all(self,name):
... return lambda: "catched: %s" % name
Here we have the __getattribute___ method will try to call the method you want to call, if it exists you will get it:
>>> a.realmethod()
I am realmethod
and if you try to call a method that does not exist, the catch_all method will be called:
>>> a = A()
>>> a.getBlablabla()
'catched: getBlablabla'
02 May 2007 10:10:01
Class A must be a new style class. This is can be achieved by making it a subclass of object (like in this example).
02 Sep 2008 16:18:45
There is also __getattr__, which catches attributes that aren't already present. Also, it can be used for any class.
class A:
def __getattr__(self, name):
return self.catch_all(name)
def realmethod(self):
print 'I am realmethod'
def catch_all(self,name):
return lambda: "catched: %s" % name
03 Sep 2008 16:51:22
Cool - I recently implemented something similar to this: http://www.whatspop.com/blo...
It also preserves ordered and keyword arguments - something that could easily be added to your catch_all.