What does the “at” (@) symbol do in Python?

前端 未结 12 963
萌比男神i
萌比男神i 2020-11-22 01:57

I\'m looking at some Python code which used the @ symbol, but I have no idea what it does. I also do not know what to search for as searching Python docs or Goo

12条回答
  •  广开言路
    2020-11-22 02:39

    In Python 3.5 you can overload @ as an operator. It is named as __matmul__, because it is designed to do matrix multiplication, but it can be anything you want. See PEP465 for details.

    This is a simple implementation of matrix multiplication.

    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([[1,3],[7,5]])
    B = Mat([[6,8],[4,2]])
    
    print(A @ B)
    

    This code yields:

    [[18, 14], [62, 66]]
    

提交回复
热议问题