1. Home
  2. Computing & Technology
  3. Python

Python Decorators, Methods, and Functions

By Al Lukaszewski, About.com

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.

5 of 7

Explore Python

More from About.com

  1. Home
  2. Computing & Technology
  3. Python
  4. Beginning Python
  5. Python Function Decorators: Defining the Decoration

©2008 About.com, a part of The New York Times Company.

All rights reserved.