Level Up Your Python Skills
Three Decorators Commonly Used in Python Custom Classes
Make your code more stylish
Introduction
Overview of Decorators
Decorators are a unique feature in Python that is not too common among other programming languages. As implied by its name, the job of a decorator is to modify another function’s behavior without affecting the decorated function’s core functionality.
Using a metaphor, let’s say the to-be-decorated function is a plain donut. You can conceptualize decorators as different coatings for the donut. No matter what the coating is — sugar, chocolate, honeybee, or whatever, a donut is still a kind of fried ring-shaped dough food.
Let’s forget about donuts (already feel wanting some sweets?) and move on to an actual example of a simple Python decorator. Through the example, we can have some ideas about what the decoration means.
>>> # Define a decorator function
>>> def show_start_end(func):
... def inner_func():
... print(f"Before calling func {func.__name__}")
... func()
... print(f"After calling func {func.__name__}")
... return inner_func
...