-8

Possible Duplicate:
Understanding Python decorators

Could you please give a short code example that explains decorators?

Community
  • 1
  • 1
Davoud Taghawi-Nejad
  • 16,142
  • 12
  • 62
  • 82
  • here's a tutorial I wrote: https://www.codementor.io/python/tutorial/introduction-to-decorators – Sheena Mar 25 '15 at 09:04

2 Answers2

5
def spam(func):
    def wrapped(*args, **kwargs):
        print "SPAM"
        return func(*args, **kwargs)
    return wrapped

@spam #this is the same as doing eggs = spam(eggs)
def eggs():
    print "Eggs?"

Notice you can also use classes to write decorators

class Spam(object):
    def __init__(self, func):
        self.func = func

    def __repr__(self):
        return repr(self.func)

    def __call__(self, *args, **kwargs):
        print "SPAM"
        return self.func(*args, **kwargs)

@Spam
def something():
    pass
Paolo
  • 20,112
  • 21
  • 72
  • 113
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
1

A decorator takes the function definition and creates a new function that executes this function and transforms the result.

@deco
def do():
    ...

is equivalent to:

do = deco(do)

Example:

def deco(func):
    def inner(letter):
        return func(letter).upper()  #upper
    return inner  # return a function object

#This
@deco
def do(number):
    return chr(number)  # number to letter
#end

# is equivalent to this
def do2(number):
    return chr(number)

do2 = deco(do2)
#end


# 65 <=> 'a'
print(do(65))
print(do2(65))
>>> B
>>> B

To understand the decorator, it is important to notice, that decorator created a new function do which is inner that executes func and transforms the result.

bolichep
  • 103
  • 2
Davoud Taghawi-Nejad
  • 16,142
  • 12
  • 62
  • 82