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)

Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python list
Python listPython list
Python list
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python set
Python setPython set
Python set
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Generators In Python
Generators In PythonGenerators In Python
Generators In Python
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

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
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 
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
 

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.
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
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종세트
 

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)
 
Python functions
Python functionsPython functions
Python functions
 
Design patterns
Design patternsDesign patterns
Design patterns
 

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

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 

Recently uploaded (20)

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 

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.