SlideShare uma empresa Scribd logo
1 de 16
http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
Decorators
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
Python Programming Essentials
© SkillBrew http://skillbrew.com
What is a decorator?
 A decorator is a callable that takes a
function as an argument and returns a
replacement function
 Useful to wrap new capabilities inside a
function
© SkillBrew http://skillbrew.com
Decorator examples
@classmethod
@staticmethod
@property
@login_required
© SkillBrew http://skillbrew.com
Creating a decorator – our objective
>>> @logger
... def foo1(x, y=1):
... return x * y
>>> foo1(5, 4)
Arguments were: (5, 4), {}
20
>>> foo1(1)
Arguments were: (1,), {}
1
© SkillBrew http://skillbrew.com
Nested functions
>>> def outer():
... x = 1
... def inner():
... print x # 1
... inner() # 2
...
>>> outer()
1
© SkillBrew http://skillbrew.com
Functions are first class objects
# all objects in Python inherit from a common
baseclass
>>> issubclass(int, object)
True
>>> def foo():
... pass
>>> foo.__class__
<type 'function'>
>>> issubclass(foo.__class__, object)
True
© SkillBrew http://skillbrew.com
Functions can be passed as arguments
>>> def add(x, y):
... return x + y
>>> def sub(x, y):
... return x - y
>>> def apply(func, x, y):
... return func(x, y)
>>> apply(add, 2, 1)
3
>>> apply(sub, 2, 1)
1
© SkillBrew http://skillbrew.com
Functions can be returned from other functions
>>> def outer():
... def inner():
... print "Inside inner"
... return inner
...
>>> foo = outer()
>>> foo
<function inner at 0x...>
>>> foo()
Inside inner
© SkillBrew http://skillbrew.com
Function closures
>>> def outer():
... x = 1
... def inner():
... print x
... return inner
>>> foo = outer()
>>> foo.func_closure
(<cell at 0x...: int object at 0x...>,)
© SkillBrew http://skillbrew.com
Function closures (2)
>>> def outer(x):
... def inner():
... print x # 1
... return inner
>>> print1 = outer(1)
>>> print2 = outer(2)
>>> print1()
1
>>> print2()
2
© SkillBrew http://skillbrew.com
Simple decorator
>>> def outer(some_func):
... def inner():
... print "before some_func"
... ret = some_func()
... return ret + 1
... return inner
>>> def foo():
... return 1
>>> decorated = outer(foo)
>>> decorated()
before some_func
2
© SkillBrew http://skillbrew.com
Logger decorator
>>> def logger(func):
... def inner(*args, **kwargs):
... print "Arguments were: %s, %s" % (args,
kwargs)
... return func(*args, **kwargs)
... return inner
© SkillBrew http://skillbrew.com
Logger decorator usage
>>> @logger
... def foo1(x, y=1):
... return x * y
>>> @logger
... def foo2():
... return 2
© SkillBrew http://skillbrew.com
Logger decorator usage (2)
>>> foo1(5, 4)
Arguments were: (5, 4), {}
20
>>> foo1(1)
Arguments were: (1,), {}
1
>>> foo2() Arguments were: (), {}
2
© SkillBrew http://skillbrew.com
References
 http://simeonfranklin.com/blog/2012/jul/1/p
ython-decorators-in-12-steps/
Python Programming Essentials - M38 - Decorators

Mais conteúdo relacionado

Destaque

Destaque (15)

Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
資料永續與交換
資料永續與交換資料永續與交換
資料永續與交換
 
從 REPL 到 IDE
從 REPL 到 IDE從 REPL 到 IDE
從 REPL 到 IDE
 
例外處理
例外處理例外處理
例外處理
 
資料結構
資料結構資料結構
資料結構
 
open() 與 io 模組
open() 與 io 模組open() 與 io 模組
open() 與 io 模組
 
從模組到類別
從模組到類別從模組到類別
從模組到類別
 
PyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 TutorialPyCon Taiwan 2013 Tutorial
PyCon Taiwan 2013 Tutorial
 
3D 之邏輯與美感交會 - OpenSCAD
3D 之邏輯與美感交會 - OpenSCAD3D 之邏輯與美感交會 - OpenSCAD
3D 之邏輯與美感交會 - OpenSCAD
 
網站系統安全及資料保護設計認知
網站系統安全及資料保護設計認知網站系統安全及資料保護設計認知
網站系統安全及資料保護設計認知
 
進階主題
進階主題進階主題
進階主題
 
常用內建模組
常用內建模組常用內建模組
常用內建模組
 
型態與運算子
型態與運算子型態與運算子
型態與運算子
 
Python 起步走
Python 起步走Python 起步走
Python 起步走
 
初學R語言的60分鐘
初學R語言的60分鐘初學R語言的60分鐘
初學R語言的60分鐘
 

Mais de P3 InfoTech Solutions Pvt. Ltd.

Mais de P3 InfoTech Solutions Pvt. Ltd. (20)

Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External Programs
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and Files
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python Programming Essentials - M15 - References
Python Programming Essentials - M15 - ReferencesPython Programming Essentials - M15 - References
Python Programming Essentials - M15 - References
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
 

Python Programming Essentials - M38 - Decorators