迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中的 @ 符号

作者:迹忆客 最近更新:2023/06/17 浏览次数:

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 中的作用。 我们希望您觉得本篇文章对您有所帮助。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便