SlideShare a Scribd company logo
1 of 12
Decorators in Python
Bhanwar Singh
Functions are Objects
• They can be assigned to other variables.
• A function can be defined inside another
function.
• A function can return another function.
• A function can take other function as an
arguments.
Decorators
• A decorator is used to wrap a function.
• It gives new functionality without changing
the original function.
Syntax :
@decorator_function
def my_func:
…………………….
…………………….
def decorater_function():
……………………….
……………………….
This is equivalent to :
my_func =
decorator_function(my_func)
How to define a decorator function?
• It takes a function (the one being decorated),
wrap it in a wrapper function and then return
the wrapper function.
def decorator_function(decorated_function):
def wrapper_function():
------------------------------------
------- some code ----------------
decorated_function()
------------------------------------
return wrapper_function
• There are user defined and in built decorators.
staticmethod and classmethod are
example of in built decorators.
• There can be more that one decorator for one
function. They are executed using stack.
Example
def helloSolarSystem(old_function):
def wrapper_function():
print "Hello Solar System"
old_function()
return wrapper_function
def helloGalaxy(old_function):
def wrapper_function():
print "Hello Galaxy"
old_function()
return wrapper_function
@helloGalaxy
@helloSolarSystem
def hello():
print "Hello World"
hello()
The output will be -
Hello Galaxy
Hello Solar System
Hello World
First all decorators are
pushed into a stack
Then, at last, they are
popped one by one.
Passing argument to the decorated function
The wrapper function should accept the arguments which are being passed to the
function being decorated.
def helloSolarSystem(old_function):
def wrapper_function(planet=None):
print "Hello Solar System"
old_function(planet)
return wrapper_function
@helloSolarSystem
def hello(planet=None):
if planet:
print "Hello "+planet
else:
print "Hello World"
hello("Mars")
hello()
Output
Hello Solar System
Hello Mars
Hello Solar System
Hello World
• You can also define wrapper for class method.
But their first argument should be self
• You can define general wrapper function using
*args, **kwargs.
Class Decorators
• Class decorators are similar to function
decorators.
• They are run at the end of a class statement to
rebind a class name to a callable.
• They can be used to manage class when they are
created.
• They can be used to insert a layer of wrapper
logic to manage instances.
• Remember both class and class instance are
object in python.
Syntax
• Syntax is similar to function decorator.
Class definition-
@class_decorator
class My_Class:
-------------
-------------
Decorator definition –
def class_decorator(cls):
---------------
---------------
This is equivalent to
My_Class =
class_decorator(My_Class)
Example – Singleton Class
instances = {} #dictionary to hold class and their only instance
def getInstance(klass,*args): #this function is used by decorator
if klass not in instances:
instances[klass]=klass(*args)
return instances[klass]
def singelton(klass): #decorator function
def onCall(*args):
return getInstance(klass,*args)
return onCall
@singelton
class Star:
def __init__(self,name):
self.name=name
#A solar system should have only one star
sun = Star('Sun')
print sun.name
taurus = Star('Taurus')
print taurus.name
Output -
Sun
Sun
Only one instance of Star is allowed.
Sources -
http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-
decorators-in-python/1594484#1594484
http://pythonconquerstheuniverse.wordpress.com/2009/08/06/introduction-to-
python-decorators-part-1/

More Related Content

What's hot (20)

Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python recursion
Python recursionPython recursion
Python recursion
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Python functions
Python functionsPython functions
Python functions
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
python Function
python Function python Function
python Function
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Templates
TemplatesTemplates
Templates
 
Python functions
Python functionsPython functions
Python functions
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 

Viewers also liked

Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Samuel Fortier-Galarneau
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsBharat Kalia
 
파이썬을 만난지 100일♥ 째
파이썬을 만난지 100일♥ 째파이썬을 만난지 100일♥ 째
파이썬을 만난지 100일♥ 째혜선 최
 
파이썬 함수 이해하기
파이썬 함수 이해하기 파이썬 함수 이해하기
파이썬 함수 이해하기 Yong Joon Moon
 
파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법Yong Joon Moon
 
Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현Daehyun (Damon) Kim
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Yong Joon Moon
 
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQtPyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt덕규 임
 
파이썬 크롤링 모듈
파이썬 크롤링 모듈파이썬 크롤링 모듈
파이썬 크롤링 모듈Yong Joon Moon
 
파이썬 Numpy 선형대수 이해하기
파이썬 Numpy 선형대수 이해하기파이썬 Numpy 선형대수 이해하기
파이썬 Numpy 선형대수 이해하기Yong Joon Moon
 
python 수학이해하기
python 수학이해하기python 수학이해하기
python 수학이해하기Yong Joon Moon
 
파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기Yong Joon Moon
 
Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706Yong Joon Moon
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기Yong Joon Moon
 
資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作台灣資料科學年會
 
파이썬 엑셀_csv 처리하기
파이썬 엑셀_csv 처리하기파이썬 엑셀_csv 처리하기
파이썬 엑셀_csv 처리하기Yong Joon Moon
 
파이썬 데이터 분석 3종세트
파이썬 데이터 분석 3종세트파이썬 데이터 분석 3종세트
파이썬 데이터 분석 3종세트itproman35
 
Advanced Python Techniques: Decorators
Advanced Python Techniques: DecoratorsAdvanced Python Techniques: Decorators
Advanced Python Techniques: DecoratorsTomo Popovic
 

Viewers also liked (20)

Python decorators
Python decoratorsPython decorators
Python decorators
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
 
파이썬을 만난지 100일♥ 째
파이썬을 만난지 100일♥ 째파이썬을 만난지 100일♥ 째
파이썬을 만난지 100일♥ 째
 
파이썬 함수 이해하기
파이썬 함수 이해하기 파이썬 함수 이해하기
파이썬 함수 이해하기
 
파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법
 
Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현Pycon2016 파이썬으로똑똑한주식투자 김대현
Pycon2016 파이썬으로똑똑한주식투자 김대현
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815
 
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQtPyCon 2015 - 업무에서 빠르게 활용하는 PyQt
PyCon 2015 - 업무에서 빠르게 활용하는 PyQt
 
파이썬 크롤링 모듈
파이썬 크롤링 모듈파이썬 크롤링 모듈
파이썬 크롤링 모듈
 
파이썬 Numpy 선형대수 이해하기
파이썬 Numpy 선형대수 이해하기파이썬 Numpy 선형대수 이해하기
파이썬 Numpy 선형대수 이해하기
 
python 수학이해하기
python 수학이해하기python 수학이해하기
python 수학이해하기
 
파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기
 
Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706Jupyter notebok tensorboard 실행하기_20160706
Jupyter notebok tensorboard 실행하기_20160706
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기
 
資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作資料視覺化之理論、賞析與實作
資料視覺化之理論、賞析與實作
 
파이썬 엑셀_csv 처리하기
파이썬 엑셀_csv 처리하기파이썬 엑셀_csv 처리하기
파이썬 엑셀_csv 처리하기
 
파이썬 데이터 분석 3종세트
파이썬 데이터 분석 3종세트파이썬 데이터 분석 3종세트
파이썬 데이터 분석 3종세트
 
Advanced Python Techniques: Decorators
Advanced Python Techniques: DecoratorsAdvanced Python Techniques: Decorators
Advanced Python Techniques: Decorators
 

Similar to Advanced Python : Decorators

PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsGraham Dumpleton
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185Mahmoud Samir Fayed
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functionsSwapnil Yadav
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
 

Similar to Advanced Python : Decorators (20)

Decorators.pptx
Decorators.pptxDecorators.pptx
Decorators.pptx
 
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating Decorators
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Advance python
Advance pythonAdvance python
Advance python
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
oops-1
oops-1oops-1
oops-1
 
Unit i
Unit iUnit i
Unit i
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185The Ring programming language version 1.5.4 book - Part 74 of 185
The Ring programming language version 1.5.4 book - Part 74 of 185
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Refactoring Chapter 6,7.pptx
Refactoring Chapter 6,7.pptxRefactoring Chapter 6,7.pptx
Refactoring Chapter 6,7.pptx
 

More from Bhanwar Singh Meena

Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.Bhanwar Singh Meena
 
Gate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper SolutionGate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper SolutionBhanwar Singh Meena
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Bhanwar Singh Meena
 
UWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio ApplicationUWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio ApplicationBhanwar Singh Meena
 
Equal Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project ReportEqual Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project ReportBhanwar Singh Meena
 
Equal Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project PresentationEqual Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project PresentationBhanwar Singh Meena
 

More from Bhanwar Singh Meena (7)

Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.
 
Quadrature amplitude modulation
Quadrature amplitude modulationQuadrature amplitude modulation
Quadrature amplitude modulation
 
Gate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper SolutionGate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper Solution
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
UWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio ApplicationUWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio Application
 
Equal Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project ReportEqual Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project Report
 
Equal Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project PresentationEqual Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project Presentation
 

Recently uploaded

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 

Advanced Python : Decorators

  • 2. Functions are Objects • They can be assigned to other variables. • A function can be defined inside another function. • A function can return another function. • A function can take other function as an arguments.
  • 3. Decorators • A decorator is used to wrap a function. • It gives new functionality without changing the original function. Syntax : @decorator_function def my_func: ……………………. ……………………. def decorater_function(): ………………………. ………………………. This is equivalent to : my_func = decorator_function(my_func)
  • 4. How to define a decorator function? • It takes a function (the one being decorated), wrap it in a wrapper function and then return the wrapper function. def decorator_function(decorated_function): def wrapper_function(): ------------------------------------ ------- some code ---------------- decorated_function() ------------------------------------ return wrapper_function
  • 5. • There are user defined and in built decorators. staticmethod and classmethod are example of in built decorators. • There can be more that one decorator for one function. They are executed using stack.
  • 6. Example def helloSolarSystem(old_function): def wrapper_function(): print "Hello Solar System" old_function() return wrapper_function def helloGalaxy(old_function): def wrapper_function(): print "Hello Galaxy" old_function() return wrapper_function @helloGalaxy @helloSolarSystem def hello(): print "Hello World" hello() The output will be - Hello Galaxy Hello Solar System Hello World First all decorators are pushed into a stack Then, at last, they are popped one by one.
  • 7. Passing argument to the decorated function The wrapper function should accept the arguments which are being passed to the function being decorated. def helloSolarSystem(old_function): def wrapper_function(planet=None): print "Hello Solar System" old_function(planet) return wrapper_function @helloSolarSystem def hello(planet=None): if planet: print "Hello "+planet else: print "Hello World" hello("Mars") hello() Output Hello Solar System Hello Mars Hello Solar System Hello World
  • 8. • You can also define wrapper for class method. But their first argument should be self • You can define general wrapper function using *args, **kwargs.
  • 9. Class Decorators • Class decorators are similar to function decorators. • They are run at the end of a class statement to rebind a class name to a callable. • They can be used to manage class when they are created. • They can be used to insert a layer of wrapper logic to manage instances. • Remember both class and class instance are object in python.
  • 10. Syntax • Syntax is similar to function decorator. Class definition- @class_decorator class My_Class: ------------- ------------- Decorator definition – def class_decorator(cls): --------------- --------------- This is equivalent to My_Class = class_decorator(My_Class)
  • 11. Example – Singleton Class instances = {} #dictionary to hold class and their only instance def getInstance(klass,*args): #this function is used by decorator if klass not in instances: instances[klass]=klass(*args) return instances[klass] def singelton(klass): #decorator function def onCall(*args): return getInstance(klass,*args) return onCall @singelton class Star: def __init__(self,name): self.name=name #A solar system should have only one star sun = Star('Sun') print sun.name taurus = Star('Taurus') print taurus.name Output - Sun Sun Only one instance of Star is allowed.