How to add a Decorator to a Class Method

Laszlo Nagy gandalf at
Tue Nov 20 19:57:37 CET 2007

> Thanks those answers make sense.  But for this function if defined
> outside the class:
>> def pre(fn):
>>     def new_func(*args, **kwargs):
>>         print "'hi'"
>>         fn(*args, **kwargs)
>>     return new_func
> Can new_func reference self?  Would self just be one of the args?

new_func is a dynamically created function. When pre() is called, it 
will return this new function. (This happens when Python tries to excute 
the "class A(object)" statement, in other words: it happens during class 
definition.) The returned function is unound, and it assigned to A.func. 
In other words, the function object is returned by pre(), but is not 
called. "new_func" will only be called when you call a.func in your 
example. When that happens, Python will find that that object 'a' has no 
direct attribute called "func", but there is one in its class "A". So it 
will call A.func as a bound method, with its "self" parameter set to the 
object that was used to call the method -- namely, "a".

Hope this helps.


More information about the Python-list mailing list