Demonstrate Python Decorators

This project was inspired by: PLEASE Use These 5 Python Decorators

Introduction

A decorator is a function that modified another function. Note: everything in Python is a object including functions. (i.e. A functions can be passed to or returned from another function.)

A More "Formal" Definitions

From: Python Decorators

In Python, a decorator is a design pattern that allows you to modify the functionality of a function by wrapping it in another function.

The outer function is called the decorator, which takes the original function as an argument and returns a modified version of it.

FYI

A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called. (From: What's the difference between an argument and a parameter?)

Project #1

Create individual programs to demonstrate the following Python decorators.

Project #2

Create a program that demonstrates a user define decorator:

  1. Create a function that prints its input arguments. Any type of data type can be passed to this function and printed. It return the number of arguments printed.

    For example

    def display_arguments(*args): c = 0 for arg in args: print(arg) c+= 1 return c

  2. Create a decorator that take the above function and converts all of its numeric input arguments to positive integers.

  3. Every format for positive and negative numeric inputs should be tested. (integer, float, scientific notation)

  4. Add a few non-numeric arguments to *args just for fun.

Project #3

Change Project #2 into an interactive program. Use a menu?

Project #4

List and describe all of Python's built-in decorators. How many are there?

Links

Primer on Python Decorators

Decorators in Python