↓ Skip to main content
Python

Python: Decorators

·1 min
Table of Contents

Let’s learn about decorators @iamdecorator

Decorators are used to modify or extend the behavior of functions and classes. They are useful for wrapping a function or class with additional functionality, such as logging, access control, performance measurement, or adding attributes. This can reduce code duplication, increase readability and maintainability.

Decorators in Python are a way to modify or extend the behavior of a function, class, or method without changing their source code.

They are implemented as special types of functions that can take another function or class as an argument, add or change its behavior, and then return the modified function or class

Decorators are indicated with the “@” symbol in front of the function or class definition.

Example
#

def logging_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Running {func.__name__} with args: {args}, {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned: {result}")
        return result
    return wrapper

@logging_decorator
def add(a, b):
    return a + b

print(add(3, 4))

Output

Running add with args: (3, 4), {}
add returned: 7
7
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Python: Class

·1 min
Learning to write Python code? A Python class is a blueprint for creating objects. It defines a set of attributes and methods that can be used to manipulate those attributes. Here’s an example of a simple Python class:

Python: Inheritance

·2 mins
Inheritance is a mechanism in object-oriented programming (OOP) that allows you to create new classes that are derived from existing classes. The derived class inherits attributes and behaviors from the base class, and can also have additional attributes and behaviors of its own.

Python: Interface

·1 min
n Python, unlike some other programming languages, there is no explicit syntax for defining interfaces. However, you can create a similar concept by defining an abstract base class (ABC) that contains abstract methods. An abstract method is a method that is declared in a base class, but has no implementation. Subclasses of the abstract base class must implement these abstract methods.