18. Mastering Python Functions and Decorators
Introduction
In Python, functions are fundamental building blocks that allow you to encapsulate code into reusable units. Decorators, introduced in Python 2.4, are a powerful feature that enables you to modify or enhance functions or methods without changing their actual code. Understanding both concepts is essential for writing clean, efficient, and maintainable Python code.
Python Functions
Defining a Function
Functions in Python are defined using the def keyword, followed by the function name and parentheses containing any parameters. The function body starts with a colon and is indented.
Example:
Calling a Function
To execute the function, you call it by its name and pass the required arguments.
Example:
Output:
Function Arguments
Functions can accept parameters, which are values passed into the function. You can specify default values, use variable-length arguments, and more.
Example:
Calling the function:
Return Values
Functions can return values using the return statement. Once a return statement is executed, the function terminates.
Example:
Calling the function:
Python Decorators
A decorator is a function that takes another function as an argument, adds some functionality, and returns a new function. They are commonly used to modify the behavior of functions or methods.
Basic Decorator
Example:
Calling the decorated function:
Output:
Using functools.wraps
To preserve the metadata of the original function, such as its name and docstring, you can use functools.wraps in your decorator.
Example:
Conclusion
Understanding functions and decorators in Python allows you to write more modular and reusable code. Functions help encapsulate logic, while decorators provide a way to modify or extend that logic without altering the original function's code. By mastering these concepts, you can enhance the readability and maintainability of your Python programs.
18. Mastering Python Functions and Decorators
coldshadow44 on 2025-10-08
(0)