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