Supercharge Your Python Functions with Simple Decorators

Learn how to use decorators to add functionality to your functions with just a few lines of code.

Max N
2 min readApr 9, 2024

Decorators are a powerful feature in Python that allow you to modify or extend the behavior of a function or method. They can make your code more concise, reusable, and easier to read by wrapping existing functions with additional functionality.

If you’re new to decorators, don’t worry! In this article, we’ll explore what decorators are and how to define your own simple decorator in just a few steps.

What is a Decorator?

A decorator is simply a callable object, such as a function, that takes another function as its argument and extends or modifies its behavior. The decorated function remains unchanged but gains new capabilities when called through the decorator.

Here’s an example of using a built-in Python decorator, @property, which allows you to access class attributes like methods:

class Person:
def __init__(self, name):
self._name = name

@property
def name(self):
return self._name

person = Person('Alice')
print(person.name) # Output: Alice

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.