Python 中 @
符号最常见的用例是装饰器。 装饰器允许您更改函数或类的行为。
@
符号也可以用作数学运算符,因为它可以在 Python 中乘以矩阵。 本教程将教您使用 Python 的 @
符号。
在 Python 的装饰器中使用 @ 符号
装饰器是一个函数,它接受一个函数作为参数,向它添加一些功能,并返回修改后的函数。
例如,请参见以下代码。
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)
装饰器修改原始函数而不改变原始函数中的任何脚本。
让我们看一下上述代码片段的实际示例。
def message(func):
def wrapper():
print("Hello Decorator")
func()
return wrapper
def myfunc():
print("Hello World")
@
符号与装饰器函数的名称一起使用。 它应该写在将被装饰的函数的顶部。
@message
def myfunc():
print("Hello World")
myfunc()
输出:
Hello Decorator
Hello World
上面的装饰器示例与这段代码做同样的工作。
def myfunc():
print("Hello World")
myfunc = message(myfunc)
myfunc()
输出:
Hello Decorator
Hello World
Python 中一些常用的装饰器是@property
、@classmethod
和 @staticmethod
。
在 Python 中使用 @ 符号乘以矩阵
从 Python 3.5 开始,@ 符号也可以用作在 Python 中执行矩阵乘法的运算符。
以下示例是 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)
输出:
[[25, 29], [42, 32]]
就是这样。 Python 中的 @
符号用于装饰器和矩阵乘法。
您现在应该了解 @
符号在 Python 中的作用。 我们希望您觉得本篇文章对您有所帮助。