[Python] Decorator

Seong-Am Kim
2 min readSep 10, 2020

I looked up about Closure last time. Today we are going to connect with this to find out how to use the Decorator in Python.
This article can be understood only when you know the concept of Closure, so if you don’t know Closure well, please look at the previous article first.

Photo by Annie Spratt on Unsplash

Why use Decorator?

Before we know how to use it, let’s find out why we use the decoder.

When designing object-oriented designs, we sometimes see when inheritance makes problem solving more difficult.
For example, different functions may be added depending on the situation, but too many implementations may require a large number of child objects.

Decorator can implement various functions by using Wrapper function without modifying existing code. Thus, the addition of complex functions can sometimes be solved by simple expressions rather than inheritance.

What is a decorator?

It is a Python phrase that literally adds various functions to existing code. Let’s learn how to use the decorator first by looking at the examples.

If you’ve read about Closure, the writing of the past time, you’ll understand the code above.

The code above is described as follows.

  1. Called decorator_func function by giving an ‘example’ argument in line 12.(Caution: the ‘example’ function has not yet been executed. The function itself has been entered as a value.)
  2. The internal wrapper_func function was returned when decorator_func was called. This was assigned to a variable named decorated_example in line 12.
  3. The wrapper_func assigned to the decorated_example was called when the decorated_example on the 13th line was called.
  4. When wrapper_func was called, input_func was called (in the 12th row, input_func was the argument that the example function was inserted).

Decorator is based on the above Closure. The codes used to describe this are as follows.

If you understood Closure, the code above would also be understandable.

Python provides a way to express the decorator more briefly.

The two codes described above print out perfectly identical results.

As described earlier, the Decorator can be easily used to add various functions.

Those who are new to the Decorator or who have never experienced a huge project may not feel the convenience of the Decorator.
In the example code, it was a simple addition of several codes, but the decorator is very useful when the situation is complicated.
When I write about design patterns, I will introduce the Decorator once more, and I will explain how to use it in more detail.

--

--