What are Decorators in Python?
What are Decorators in Python?
Decorators in Python are a powerful and versatile feature that allow programmers to modify or enhance the behavior of functions or methods without permanently changing their code. Essentially, a decorator is a higher-order function that takes another function as an argument, wraps its behavior with additional code, and returns a new function with the extended functionality.
The primary purpose of using decorators is to adhere to the principles of code reusability and separation of concerns. Instead of repeatedly writing the same code across multiple functions, decorators enable you to define that behavior once and apply it wherever needed.
Here's a basic example of a decorator:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
In this example, my_decorator
is a decorator that adds behavior before and after the say_hello
function is called, without modifying the function itself. The @my_decorator
syntax is syntactic sugar for say_hello = my_decorator(say_hello)
.
Decorators can also accept arguments and return values, and they can be used to implement functionality such as logging, access control, caching, and more. They are applied ...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào