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

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaEdureka!
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#Hemant Chetwani
 
Friend function
Friend functionFriend function
Friend functionzindadili
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming Raghunath A
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
Composition in OOP
Composition in OOPComposition in OOP
Composition in OOPHuba Akhtar
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programmingSrinivas Narasegouda
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python Home
 

What's hot (20)

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#
 
Friend function
Friend functionFriend function
Friend function
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Composition in OOP
Composition in OOPComposition in OOP
Composition in OOP
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
 

Viewers also liked

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
 
Python 이해하기 20160815
Python 이해하기 20160815Python 이해하기 20160815
Python 이해하기 20160815Yong Joon Moon
 

Viewers also liked (20)

Python decorators
Python decoratorsPython decorators
Python decorators
 
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
 
Python 이해하기 20160815
Python 이해하기 20160815Python 이해하기 20160815
Python 이해하기 20160815
 

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

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 

Recently uploaded (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 

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.