[Python-talk] functional programming, decorators and properties in 'new classes'

Python python at venix.com
Sat Sep 24 15:03:56 EDT 2005


Kent pointed out this cookbook comment on the Python Tutor list.

Alternate without a new decorator, Benji York, 2005/05/27
Here's a way that doesn't require any new decorators:
(from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698)

class Example(object):
    @apply
    def myattr():
        doc = """This is the doc string."""
        def fget(self):
            return self._value
        def fset(self, value):
            self._value = value
        def fdel(self):
            del self._value
        return property(**locals())

I think the easiest way to see what is going on is to work through the
code backwards.  

The last line calls the builtin property function.  The property
function allows you to tie get/set/del methods and a doc string to an
attribute of a class.  The idea is to use methods for references to
obj.myattr.  In the original cookbook example, an angle is returned as
degrees or radians depending upon which name you use to reference it.

The typical coding of property looks like:

locals() is a builtin function that returns the local variables and
their values as a dictionary.  The names were *carefully* chosen to
match the argument names of the property function.  The ** allows us to
use a dictionary to supply the named arguments.

The function name (myattr) should really be a descriptive name for the
property.

@ on the line before a function definition marks a decorator.  It is
followed by the name of the function that will do the decorating.  The
rules for decorating are that the defined function will be passed into
the decorator.  The decorator will return a function which will take the
place of the original.  One use for a decorator would be to add logging
to the original function.

In this case we are using apply to run the function that got passed in.
Apply simply executes the function and returns the results.  However,
the myattr function was carefully written to return the results of the
pro

-- 
Lloyd Kvam
Venix Corp



More information about the Python-talk mailing list