Monday, 1 May 2017

Decorator's in python

Decorator's:


  • This concept is same like as Closure's concept in python.
  • every function it self as a one object.
  • Decorator's(meta programs) takes the function and add some Functionalities and it's return's.


Manual implementation of Decorator's:


def make_pretty(func):

    def inner( ):

        print("I Got Decorated")

        func( )

    return inner

def ordinary( ):

    print("I Am Ordinary")

ordinary( )

pretty=make_pretty(ordinary)

pretty( )



I Am Ordinary

I Got Decorated

I Am Ordinary

Shortcut implementation of Decorator:

def make_pretty(func):

    def inner( ):

        print("I Got Decorated")

        func( )

    return inner

@make_pretty

def ordinary( ):

    print("I Am Ordinary")

ordinary( )


I Got Decorated

I Am Ordinary

Combination of both Closure and Decorator:

def smart_divide(func):

    def inner(a,b):

        print("I Am Going To Divide ", a ,"with", b)

        if b= =0:

            print("Whooop's! cannot Divide")

            return

        return func(a,b)

    return inner

@smart_divide

def divide(a,b):

    return a/b

p=divide(10,0)

print(p)


I Am Going To Divide  10 with 0

Whooop's! cannot Divide

None

def smart_divide(func):

    def inner(a,b):

        print("I Am Going To Divide ", a ,"with", b)

        if b= =0:

            print("Whooop's! cannot Divide")

            return

        return func(a,b)

    return inner

@smart_divide

def divide(a,b):

    return a/b

p=divide(10,2)

print(p)

I Am Going To Divide  10 with 2

5.0




No comments:

Post a Comment