Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Decorators

Python Decorators

A basic understanding of Python Decorators.

Eloy Zuniga Jr.

June 19, 2012
Tweet

More Decks by Eloy Zuniga Jr.

Other Decks in Technology

Transcript

  1. Basic definition Decorator is a function that takes a function

    as a parameter and returns a function Tuesday, June 19, 12
  2. Basic definition Decorator is a function that takes a function

    as a parameter and returns a function Is a function. Takes a function. Returns a function Tuesday, June 19, 12
  3. def in_bed(func): def f(): return ‘%s In bed.’ % func()

    return f Change output Tuesday, June 19, 12
  4. def in_bed(func): def f(): if f.in_pool: return ‘%s In pool.’

    % func() return ‘%s In bed.’ % func() f.in_pool = False return f Add attributes Tuesday, June 19, 12
  5. def in_bed(func): def f(*args, **kwargs): if args or kwargs: raise

    Exception(‘wat?’) return ‘%s In bed.’ % func() return f Validate Tuesday, June 19, 12
  6. def luke_quote(): return “I’m Luke SkyWalker, I’m here to rescue

    you.” Decorate @in_bed Tuesday, June 19, 12
  7. def luke_quote(): return “I’m Luke SkyWalker, I’m here to rescue

    you.” Decorate @in_bed @no_inbreeding Tuesday, June 19, 12
  8. def luke_quote(): return “I’m Luke SkyWalker, I’m here to rescue

    you.” Decorate @in_bed(with=”lightsaber”) @in_bed Tuesday, June 19, 12