【问题标题】:Understanding the use of multiple python decorators in a single statement了解在单个语句中使用多个 python 装饰器
【发布时间】:2021-02-10 19:50:36
【问题描述】:

我最近遇到了一个与下面给出的非常相似的代码 sn-p:

def abc(a,b,c):
    a1 = a[:, :1]
    b1 = b[:1, :]
    c1 = c[:1, :]
   
    a2 = a1.conj().transpose()
    b2 = c1.conj().transpose()
   
    d = np.linalg.inv(np.sqrt(b1))
   
    e = d @ a2 @ b @ b2 @ d
   
    return e

a,b,c 是 numpy 数组。

我正在尝试了解 python 装饰器,并从 this question 中学到了一点。

但是我无法弄清楚变量e 是如何定义的。到底发生了什么?

我是 Python 的初学者。据我所知,装饰器包裹着一个函数,函数作为参数传递。但在这里,这些都是 numpy 数组。

任何解释变量 e 时到底发生了什么或在一行中有多个装饰器的特定索引的含义都会非常有帮助。

【问题讨论】:

  • @ 不是这里的装饰器。它是运算符 - 矩阵乘法docs.python.org/3/library/operator.html#operator.matmul
  • 哦,好吧。谢谢。是否等同于使用 np.matmul() ?还是只是推荐的语法?
  • 另外,我应该只回答我自己的问题还是删除它,因为这是一个错误的问题?抱歉,堆栈溢出的新手。
  • 是的,它就像 matmul。来自numpy documentationThe matmul function implements the semantics of the @ operator introduced in Python 3.5 following PEP465. 但就个人而言,我会使用np.matmul 函数,因为它更清晰
  • 非常感谢您的 cmets。这清除了一切。

标签: python python-3.x function decorator python-decorators


【解决方案1】:

e = d @ a2 @ b @ b2 @ d 行与 Python 装饰器无关。这里的@ 字符是Python @ 运算符:https://docs.python.org/3/library/operator.html#operator.matmul

链接到 PEP-465:https://www.python.org/dev/peps/pep-0465/

来自 numpy 文档link

matmul函数实现@运算符的语义 在 PEP465 之后的 Python 3.5 中引入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-15
    • 2016-07-26
    • 2020-10-14
    • 2018-06-21
    • 2015-02-22
    • 1970-01-01
    • 2020-10-15
    • 2018-10-03
    相关资源
    最近更新 更多