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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迹忆客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值