Skip to main content

Decorators

 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 the wrapped function, without permanently modifying it. But before diving deep into decorators let us understand some concepts that will come in handy in learning the decorators.


Following are important facts about functions in Python that are useful to understand decorator functions.

  1. In Python, we can define a function inside another function.
  2. In Python, a function can be passed as parameter to another function (a function can also return another function).

# A Python program to demonstrate that a function
# can be defined inside another function and a
# function can be passed as parameter.
  
# Adds a welcome message to the string
    def messageWithWelcome(str):
  
        # Nested function
        def addWelcome():
            return "Welcome to "
  
        # Return concatenation of addWelcome()
        # and str.
        return  addWelcome() + str
  
    # To get site name to which welcome is added
    def site(site_name):
        return site_name
  
    print messageWithWelcome(site("Python"))

Output: "Welcome to python"



Function Decorator

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. For example, above code can be re-written as following.

We use @func_name to specify a decorator to be applied on another function.


# Adds a welcome message to the string
# returned by fun(). Takes fun() as
# parameter and returns welcome().
def decorate_message(fun):
  
    # Nested function
    def addWelcome(site_name):
        return "Welcome to " + fun(site_name)
  
    # Decorator returns a function
    return addWelcome
  
@decorate_message
def site(site_name):
    return site_name;
  
# Driver code
  
# This call is equivalent to call to
# decorate_message() with function
# site("GeeksforGeeks") as parameter
print site("python")


Output: "Welcome to python"

The above two programs has same results but have 2 different approaches.

Decorators can also be useful to attach data (or add attribute) to functions.
# A Python example to demonstrate that
# decorators can be useful attach data
  
# A decorator function to attach
# data to func
def attach_data(func):
       func.data = 3
       return func
  
@attach_data
def add (x, y):
       return x + y
  
# Driver code
  
# This call is equivalent to attach_data()
# with add() as parameter
print(add(2, 3))
  
print(add.data)


Output:

5
3




Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ ...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...