Mark As Completed Discussion

What is a decorator in Python?

Python offers a unique feature called decorators.

Let's start with an analogy before getting to the technical definition of the decorators. When we mention the word "decorator", what enters your mind? Well, likely something that adds beauty to an existing object. An example is when we hang a picture frame to a wall to enhance the room.

Decorators in Python add some feature or functionality to an existing function without altering it.

Let's say we have the following simple function that takes two numbers as parameters and divides them.

PYTHON
1def divide(first, second):
2    print ("The result is:", first/second)

Now if we call this function by passing the two values 16 and 4, it will return the following output:

PYTHON
1divide(16, 4)

The output is:

PYTHON
1The result is: 4.0
PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment