SlideShare a Scribd company logo
Decorators
Decorators
• to add functionality to an existing code.
• Metaprogramming as a part of the program
tries to modify another part of the program at
compile time.
• Decorators allow you to make simple
modifications to callable objects like functions,
methods, or classes.
• Decorators are very powerful and useful tool
in Python since it allows programmers to
modify the behavior of function or class.
• Decorators allow us to wrap another function
in order to extend the behavior of wrapped
function, without permanently modifying it.
• In Decorators, functions are taken as the
argument into another function and then
called inside the wrapper function
Types
• Two different kinds of decorators in Python:
– Function decorators
– Class decorators
Function Decorators
• A decorator is a function that takes a function
as its only parameter and returns a function.
This is helpful to “wrap” functionality with the
same code over and over again.
Sample
def decorator_function(org_fun):
def wrapper_function():
print("wrapper executed this before {}".format(org_fun.__name__))
return org_fun()
return wrapper_function
@decorator_function
def display():
print("display functions")
display()
Class Decorators
• If you want to create a callable returning
another callable, the function decorator
approach is easier. If you want the return to
be a function, function decorators should be
preferred, however if you want the decorator
to return a custom object that does something
different to what a function does, in that case
a class decorator should be used
Sample Code
class decorator_class(object):
def __init__(self,org_fun):
self.org_fun=org_fun
def __call__(self):
print("wrapper executed this before {}".format(self.org_fun.__name__))
return self.org_fun)
@decorator_class
def display():
print("display functions")
display()
Chaining Decorators
• A function can be decorated multiple times with different (or
same) decorators.
• The chaining of decorator is similar to how multiple
inheritance can be used to construct classes We can write as
many decorator as we want and include them one by one in
decoration line with decoration syntax before the definition of
function to be decorated.
def makebold(f):
return lambda: "<b>" + f() + "</b>"
def makeitalic(f):
return lambda: "<i>" + f() + "</i>"
@makebold
@makeitalic
def say():
return "Hello"
print say()
Decorator Arguments
• Passing parameters in function
def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
@smart_divide
def divide(a,b):
return a/b
def works_for_all(func):
def inner(*args, **kwargs):
print("I can decorate any function")
return func(*args, **kwargs)
return inner
@works_for_all
def divide(a,b):
print(a/b)
• *args (Non Keyword
Arguments)
– Tuple values are
passed inside the
function
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
• **kwargs (Keyword
Arguments)
– Dict values are passed
def intro(**data):
print("nData type of
argument:",type(data))
for key, value in
data.items():
print("{} is
{}".format(key,value))
intro(Firstname="Sita",
Lastname="Sharma", Age=22,
Phone=1234567890)
intro(Firstname="John",
Lastname="Wood",
Email="johnwood@nomail.co
m", Country="Wakanda",
Age=25,
Phone=9876543210)**kwarg
s (Keyword Arguments)
def star(func):
def inner(*args, **kwargs):
print("*" * 30)
func(*args, **kwargs)
print("*" * 30)
return inner
def percent(func):
def inner(*args, **kwargs):
print("%" * 30)
func(*args, **kwargs)
print("%" * 30)
return inner
@star
@percentdef
printer(msg):
print(msg)
printer("Hello")
class ClassDecorator(object):
def __init__(self, arg1, arg2):
print("Arguements passed to decorator {} and {}".format(arg1, arg2))
self.arg1 = arg1
self.arg2 = arg2
def __call__(self, foo, *args, **kwargs):
def inner_func(*args, **kwargs):
print("Args passed inside decorated function {} and {}".format(self.arg1,
self.arg2))
return foo(*args, **kwargs)
return inner_func
@ClassDecorator("arg1", "arg2")
def print_args(*args):
for arg in args:
print(arg)

More Related Content

PPTX
Advanced Python : Decorators
PPTX
MFA CSE FONModularity_and_Functions.pptx
PDF
Chapter Functions for grade 12 computer Science
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PPTX
Functions and Modules.pptx
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
UNIT 3 python.pptx
Advanced Python : Decorators
MFA CSE FONModularity_and_Functions.pptx
Chapter Functions for grade 12 computer Science
CHAPTER 01 FUNCTION in python class 12th.pptx
Functions and Modules.pptx
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
UNIT 3 python.pptx

Similar to Decorators.pptx (20)

PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
PDF
Functions2.pdf
PDF
3-Python Functions.pdf in simple.........
PPTX
Functions in python
PPTX
Chapter One Function.pptx
PDF
Dive into Python Functions Fundamental Concepts.pdf
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
PPTX
Decided to go to the 65 and the value of the number
PPT
functions _
PDF
Python functions
PPTX
Mastering Python lesson 4_functions_parameters_arguments
PPTX
Python_Functions_Unit1.pptx
PPTX
advancedfunctionalprogramming(lamba).pptx
PPTX
Functions in Python Programming Language
PPTX
Functions_new.pptx
PPT
Chapter Introduction to Modular Programming.ppt
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
PDF
ch-3 funtions - 1 class 12.pdf
PPTX
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
PPTX
CPP06 - Functions
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
Functions2.pdf
3-Python Functions.pdf in simple.........
Functions in python
Chapter One Function.pptx
Dive into Python Functions Fundamental Concepts.pdf
cbse class 12 Python Functions2 for class 12 .pptx
Decided to go to the 65 and the value of the number
functions _
Python functions
Mastering Python lesson 4_functions_parameters_arguments
Python_Functions_Unit1.pptx
advancedfunctionalprogramming(lamba).pptx
Functions in Python Programming Language
Functions_new.pptx
Chapter Introduction to Modular Programming.ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
ch-3 funtions - 1 class 12.pdf
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
CPP06 - Functions
Ad

Recently uploaded (20)

PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
Sunset Boulevard Student Revision Booklet
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PDF
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
IMMUNIZATION PROGRAMME pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Congenital Hypothyroidism pptx
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
How to Manage Bill Control Policy in Odoo 18
Open Quiz Monsoon Mind Game Final Set.pptx
Sunset Boulevard Student Revision Booklet
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
Module 3: Health Systems Tutorial Slides S2 2025
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Week 4 Term 3 Study Techniques revisited.pptx
IMMUNIZATION PROGRAMME pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
O7-L3 Supply Chain Operations - ICLT Program
Renaissance Architecture: A Journey from Faith to Humanism
Congenital Hypothyroidism pptx
Revamp in MTO Odoo 18 Inventory - Odoo Slides
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Cardiovascular Pharmacology for pharmacy students.pptx
Introduction and Scope of Bichemistry.pptx
NOI Hackathon - Summer Edition - GreenThumber.pptx
How to Manage Bill Control Policy in Odoo 18
Ad

Decorators.pptx

  • 2. Decorators • to add functionality to an existing code. • Metaprogramming as a part of the program tries to modify another part of the program at compile time. • Decorators allow you to make simple modifications to callable objects like functions, methods, or classes.
  • 3. • Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. • Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. • In Decorators, functions are taken as the argument into another function and then called inside the wrapper function
  • 4. Types • Two different kinds of decorators in Python: – Function decorators – Class decorators
  • 5. Function Decorators • A decorator is a function that takes a function as its only parameter and returns a function. This is helpful to “wrap” functionality with the same code over and over again.
  • 6. Sample def decorator_function(org_fun): def wrapper_function(): print("wrapper executed this before {}".format(org_fun.__name__)) return org_fun() return wrapper_function @decorator_function def display(): print("display functions") display()
  • 7. Class Decorators • If you want to create a callable returning another callable, the function decorator approach is easier. If you want the return to be a function, function decorators should be preferred, however if you want the decorator to return a custom object that does something different to what a function does, in that case a class decorator should be used
  • 8. Sample Code class decorator_class(object): def __init__(self,org_fun): self.org_fun=org_fun def __call__(self): print("wrapper executed this before {}".format(self.org_fun.__name__)) return self.org_fun) @decorator_class def display(): print("display functions") display()
  • 9. Chaining Decorators • A function can be decorated multiple times with different (or same) decorators. • The chaining of decorator is similar to how multiple inheritance can be used to construct classes We can write as many decorator as we want and include them one by one in decoration line with decoration syntax before the definition of function to be decorated.
  • 10. def makebold(f): return lambda: "<b>" + f() + "</b>" def makeitalic(f): return lambda: "<i>" + f() + "</i>" @makebold @makeitalic def say(): return "Hello" print say()
  • 11. Decorator Arguments • Passing parameters in function def smart_divide(func): def inner(a,b): print("I am going to divide",a,"and",b) if b == 0: print("Whoops! cannot divide") return return func(a,b) return inner @smart_divide def divide(a,b): return a/b
  • 12. def works_for_all(func): def inner(*args, **kwargs): print("I can decorate any function") return func(*args, **kwargs) return inner @works_for_all def divide(a,b): print(a/b)
  • 13. • *args (Non Keyword Arguments) – Tuple values are passed inside the function def adder(*num): sum = 0 for n in num: sum = sum + n print("Sum:",sum) adder(3,5) adder(4,5,6,7) adder(1,2,3,5,6) • **kwargs (Keyword Arguments) – Dict values are passed def intro(**data): print("nData type of argument:",type(data)) for key, value in data.items(): print("{} is {}".format(key,value)) intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890) intro(Firstname="John", Lastname="Wood", Email="[email protected] m", Country="Wakanda", Age=25, Phone=9876543210)**kwarg s (Keyword Arguments)
  • 14. def star(func): def inner(*args, **kwargs): print("*" * 30) func(*args, **kwargs) print("*" * 30) return inner def percent(func): def inner(*args, **kwargs): print("%" * 30) func(*args, **kwargs) print("%" * 30) return inner @star @percentdef printer(msg): print(msg) printer("Hello")
  • 15. class ClassDecorator(object): def __init__(self, arg1, arg2): print("Arguements passed to decorator {} and {}".format(arg1, arg2)) self.arg1 = arg1 self.arg2 = arg2 def __call__(self, foo, *args, **kwargs): def inner_func(*args, **kwargs): print("Args passed inside decorated function {} and {}".format(self.arg1, self.arg2)) return foo(*args, **kwargs) return inner_func @ClassDecorator("arg1", "arg2") def print_args(*args): for arg in args: print(arg)