1. Technology

Python Decorators, Methods, and Functions


5 of 7

Defining the Decoration

In order to use a decorator, one must first have functions to serve that purpose. Let's create two simple functions, each receives a function as its first and only argument and then creates an attribute for that function object.

 >>> def decorate(function): 
 ...    function.attribute = 'I live to decorate ' + function.__name__ + '.' 
 ...    return function 
 >>> def ornament(function): 
 ...    function.mantra = 'My existence is as an ornament for ' + function.__name__ + '.' 
 ...    return function 

If you need to refresh yourself on the attributes and methods of function objects, simply type the following at the Python shell prompt (after defining decorate): dir(decorate). One of the attributes is __name__. You will want to pay attention to the value of this attribute in the output of the program.

  1. About.com
  2. Technology
  3. Python
  4. Beginning Python
  5. Python Function Decorators: Defining the Decoration

©2014 About.com. All rights reserved.