Python @ DjangoSpin

PyPro #75 Decorator Design Pattern

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Decorator Design Pattern in Python

Decorator Design Pattern in Python

Write a Python program to implement Decorator Design Pattern.

Decorator

def decorateMyFunction(originalFunction):
    '''Decorates a function by wrapping its return value in a pair of HTML paragraph tags.'''
    def addAdditionalText():
        # Obtain string returned by original function
        textFromOriginalFunction = originalFunction()
        # Adding new functionality to the function being decorated
        return "<p>" + textFromOriginalFunction + "</p>"
    return addAdditionalText
 
@decorateMyFunction
def functionToBeDecorated():
    '''A simple function that returns a string.'''
    return "Hi there!"
 
print( functionToBeDecorated() )                  # OUTPUT: <p>Hi there!</p>

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply