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

oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Friend function
Friend functionFriend function
Friend functionzindadili
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONLalitkumar_98
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 

What's hot (20)

oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Python Modules
Python ModulesPython Modules
Python Modules
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Sets in python
Sets in pythonSets in python
Sets in python
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Friend function
Friend functionFriend function
Friend function
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Python functions
Python functionsPython functions
Python functions
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Python tuple
Python   tuplePython   tuple
Python tuple
 

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)
 
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

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 

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.