Python Tutorial

Tuesday, October 9, 2012

Design pattern in python : decorator pattern

Python decorator allow us to modify or inject code into a function and classes. It is very easy to use.
Here something we need to remember, __init__ function exceute when decorator is declare and __call__ execute when function('doSomethingCopy') will call independently. We can also call function('doSomethingCopy') from anywhere of the decorator class('MyDecorator').

class MyDecorator(object):
    def __init__(self, f):
        print "This line will call on decoration"

    def __call__(self,p,q): # here we pass the function parameter 
        print "This line will work when we call the function 'doSomething' "

def doSomething(a,b):
    print "I am doing something"
    print "A ",a," B ",b


This line will call on decoration
This line will work when we call the function 'doSomething' 
I am doing something
A  4  B  5


Post a Comment