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):
        self.doSomethingCopy=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' "
        self.doSomethingCopy(p+1,q+1)

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

doSomething(3,4)


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

0 comments:

Post a Comment