What does the "at" (@) symbol do in Python?
In Python, the "at" (@) symbol is used to decorate a function.
In Python, the "at" (@) symbol is used to decorate a function. A decorator is a design pattern in Python that allows modifying the behavior of a function or class without changing its code. Here's an example of a decorator in Python:
an example of a decorator in Python
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()
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
In this example, the my_decorator function is a decorator. It takes a function as an argument, defines a new function wrapper that does something before and after the original function is called, and returns the new function. The @my_decorator line above the say_hello function is the decorator syntax, which tells Python to apply the my_decorator function as a decorator to the say_hello function. When you call say_hello(), it will first run the code in the wrapper function, then call the say_hello function, and then run the code in the wrapper function again.