Decorator help

88888 Dihedral dihedral88888 at googlemail.com
Sat Mar 30 23:06:25 EDT 2013


Jason Swails於 2013年3月28日星期四UTC+8上午4時33分08秒寫道:
> On Wed, Mar 27, 2013 at 3:49 PM, Joseph L. Casale <jca... at activenetwerx.com> wrote:
> 
> I have a class which sets up some class vars, then several methods that are passed in data
> 
> and do work referencing the class vars.
> 
> 
> 
> 
> 
> I want to decorate these methods, the decorator needs access to the class vars, so I thought
> 
> about making the decorator its own class and allowing it to accept args.
> 
> 
> 
> 
> 
> I was hoping to do all the work on in_data from within the decorator, which requires access
> 
> to several MyClass vars. Not clear on the syntax/usage with this approach here, any guidance
> 
> would be greatly appreciated!
> 
> 
> 
> My guess is that you don't quite 'get' decorators yet (since I remember similar types of questions when trying to learn them myself).  Decorators execute when the class type itself is being built (e.g., when a module is first imported at runtime).  So decorators will never take instance variables as arguments (nor should they, since no instance can possibly exist when they execute).  Bear in mind, a decorator should take a callable as an argument (and any number of 'static' parameters you want to assign it), and return another callable.
> 
> 
> 
> I provide an example decorator using the format the I typically adopt below (where the decorator is a simple function, not a class):
> 
> 
> def my_decorator(fcn):

I might add default parameters here  if I am programming 
in python to save the troubles of subclassing
similar decorators.

But that is only the stylish problem in python.

I might need to translate the decorator part into cython 
or c/c++ in the future.


>    """ Decorator for a function """
> 
>    def new_fcn(self, *args, **kwargs):
>       """ This is the new function that we will return. """
>       # You can access any instance variables here
>       returnval = fcn(self, *args, **kwargs)
> 
>       # Do anything else here with instance variables
>       return returnval # or any other return value you want
>    
>    return new_fcn
> 
> 
> Notice here I define a new_fcn callable function that takes self and an arbitrary argument/keyword-argument list, and I return this function (which does not get called) to replace the function I passed in.  You can use instance variables inside new_fcn since new_fcn is called by instances of MyClass.  This is a very simple type of decorator, but hopefully helps illustrate what decorators are.  There is a particularly good thread on SO with information about decorators here: http://stackoverflow.com/questions/739654/understanding-python-decorators
> 
> 
> 
> Hope this helps,
> Jason




More information about the Python-list mailing list