In The voodoo of reflection I briefly described how to use reflection to add functionality to existing methods. I gave some code-snippet showing how to decorate functions to realize the same effect. I’ve commented that the example given would have to be extended to decorate methods (functions of objects). Here is a snippet showing how to decorate methods.
class Test(object):
def meth1(self):
print ' test meth1'
def meth2(self, name):
print ' test meth2'
def __getattribute__(self, attrName):
lookedup = object.__getattribute__(self, attrName)
if callable(lookedup):
print ' *debugging %s' % attrName
return lookedup
The snippet defines a class Test which inherits from class object. The class defines two methods that simply print some text to let you know they got called. The method __getattribute__ is the trick here. It is called each time some attribute of an instance of that class is accessed. Methods are attributes, too. self functions just like this in Java. It is a reference to the current object. Since attribute-access is caught by this method on this level of the inheritance-hierarchy one has to call the super-method to get the attribute. Otherwise one would create an infinite recursion (calling Test.__getattribute__ all the time). So lookedup contains the value of the attribute that was accessed (attrName is the name of that attribute, e.g. a variable-name or method-name). callable checks whether that value is something that can be called (like functions or methods). If it can be called, then debugging-information is displayed and the result of calling the callable is returned.
Note that using this method one cannot display information after calling the method. That’s because __getattribute__ just returns the object to be called, we intercept that but actually do not change the attribute-value that gets returned. That’s an important difference to the decorator for functions discussed in the previous post on black magic, where the actual method-object was replaced and extended.
The complete source is available. Since the ‘pseudocode’ given above and in my last post is acuallty Python, there is more on __getattribute__ in More attribute access for new-style classes: __getattribute__.
I am actually quite new to python and still have lots to learn. So if you find an error or possibilities of improvement in what I’ve written, please, let me know.





{ 1 } Trackback
[...] reflection I shortly described how this could be achieved by using reflection in java. In Interludium pro magus nigris we’ve changed the access to objec [...]Post a Comment