对于创建为的稀疏矩阵
from scipy import sparse
M = sparse.rand(100, 100, format='csr')
有没有一种方法可以防止在构造后对其进行修改?也就是说,禁止执行诸如M[0, 0] = 1
之类的操作。
我的动机是将M
存储在对象G
中,该对象具有依赖于M
的其他属性。如果M
发生变化,则必须重新计算这些属性,否则G
将处于非相干状态。当M
完全定义G
时,我宁愿禁止修改,并迫使我的用户从他们的新G
实例化另一个M
。在代码中:
class G:
def __init__(self, M):
self.M = M
self.d = M.sum(axis=0)
# Normal usage.
g = G(M)
print(g.M.toarray())
print(g.d)
# Modification out of my control that leads to an incoherent state.
M[0, 0] = 1
print(g.M.toarray())
print(g.d)