At Tuesday 22/8/2006 17:19, Wolfgang Draxinger wrote:
I'm just reading the python language reference and came around
the term "decorated functions", but I have no idea, for what
they could be used.
A decorator takes a function/method/callable, "decorates" (modifies)
it in a certain way, and returns it.
@classmethod and @staticmethod are examples: they take a (normal)
method, and transform it into another thing.
You can write your own decorators. An example similar to one
discussed on this list a few days ago: suppose you have a pure
function taking a long time to compute; you could save the results in
a dictionary using the arguments as key, and retrieve them later when
a call is made exactly with the same arguments. This is a known
pattern ("memoize").
def memoized(function):
function.cache={}
def f(*args):
try: return function.cache[args]
except KeyError:
result = function.cache[args] = function(*args)
return result
return f
@memoized
def fibo(n):
time.sleep(2) # a sloooooow function
if n<2: return 1
return fibo(n-1)+fibo(n-2)
The original function is fibo() - it works OK but assume it's slow.
So you "decorate" it with @memoized to improve performance.
(This is just an example, of course - I'm not saying memoizing is the
right thing to do here, nor this is the best way to do it... just to
demonstrate what a decorator could be used for)
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
--
http://mail.python.org/mailman/listinfo/python-list