Python Tutorial: Usage of @ symbol

The most common usage of 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 math operator, as it can multiply matrices in Python. This tutorial will teach you how to use Python's @ symbol.

Use the @ symbol in the decorator

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 script in the original function.

Let's see 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 @ sign 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 commonly used decorators in Python are: @property, @classmethod, and @staticmethod.

Matrix multiplication using the @ symbol

Starting with 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 #Python小白学习交流群:153708845
        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 all. The @ symbol in Python is used for decorators and matrix multiplication.

You should now understand what the @ symbol does in Python. We hope you find this tutorial helpful.

Guess you like

Origin blog.csdn.net/qdPython/article/details/132188101