Python 中的 @ 符号
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 中的作用。 我们希望您觉得本篇文章对您有所帮助。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串