BUG: 通过嵌套列表切片设置对象数组会不必要地调用对象的 `__array__` 方法
作者: chriseclectic创建于 2023年8月4日更新于 2026年9月30日
标签00 - Bugsustain-2026
import numpy as np class Pauli: """Basic N-qubit Pauli"""
_mats = {
"I": np.eye(2, dtype=complex),
"X": np.array([[0, 1], [1, 0]], dtype=complex),
"Y": np.array([[0, -1j], [0, 1j]], dtype=complex),
"Z": np.array([[1, 0], [0, -1]], dtype=complex),
}
def __init__(self, label):
"""Initialize a Pauli from a string label"""
self.label = label
def __repr__(self):
return f"Pauli({self.label})"
def to_matrix(self):
"""Convert to a (2**N, 2**N) complex matrix"""
ret = np.eye(1, dtype=complex)
for i in self.label:
ret = np.kron(self._mats[i], ret)
return ret
def __array__(self, dtype=None):
# Print to know when the `__array__` method is invoked
print("Pauli.__array__ called")
mat = self.to_matrix()
if dtype:
mat = mat.astype(dtype)
return mat
def __eq__(self, other):
if isinstance(other, Pauli):
return self.label == other.label
return FalseCreate an array-like nested list of Pauli objects
nq = 1 paulis = [[Pauli(nq * "I"), Pauli(nq * "X")], [Pauli(nq * "Y"), Pauli(nq * "Z")]]
…
内容来源: numpy/numpy