SoFunction
Updated on 2024-11-13

A short summary of the usage of the @ symbol in Python

The most common use case for the @ symbol in Python is in decorators. A decorator allows you to change the behavior of a function or class.

The @ symbol can also be used as a mathematical operator as it can multiply matrices in Python. This tutorial will teach you how to use Python's @ symbol.

Using the @ symbol in decorators

A decorator is a function that takes a function as an argument, adds some functionality to it, and returns the modified function.

For example, see the code below.

def decorator(func):
    return func
@decorator
def some_func():
    pass

This is equivalent to the code below.

def decorator(func):
    return func
def some_func():
    pass
some_func = decorator(some_func)

The decorator modifies the original function without changing any of the script in the original function.

Let's look at a practical example of the above code snippet.

def message(func):
    def wrapper():
        print("Hello Decorator")
        func()
    return wrapper
def myfunc():
    print("Hello World")

The @ symbol is used with the name of the decorator function. It should be written at the top of the function that will be decorated.

@message
def myfunc():
	print("Hello World")
myfunc()

Output:

Hello Decorator
Hello World

The decorator example above does the same job as this code.

def myfunc():
    print("Hello World")
myfunc = message(myfunc)
myfunc()

Output:

Hello Decorator
Hello World

Some common decorators in Python are @property , @classmethod , and @staticmethod .

Matrix multiplication using the @ symbol

As of Python 3.5, the @ symbol can also be used as an operator to perform matrix multiplication in Python.

The following example is a simple implementation of matrix multiplication in Python.

class Mat(list):
    def __matmul__(self, B):
        A = self
        return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
                    for j in range(len(B[0])) ] for i in range(len(A))])
A = Mat([[2,5],[6,4]])
B = Mat([[5,2],[3,5]])
print(A @ B)

Output:

[[25, 29], [42, 32]]

That's it.The @ symbol in Python is used for decorators and matrix multiplication.

Now you should understand what the @ symbol does in Python. We hope you found this tutorial helpful.

To this point this article on the use of Python @ symbol summary of the article is introduced to this, more related Python @ symbol content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!