![](/img/trans.png)
[英]How to properly pass a scipy.sparse CSR matrix to a cython function?
[英]How to inherit from a scipy.sparse matrix properly?
我嘗試通過多重繼承將自己的方法和屬性添加到稀疏矩陣中。 但是我發現算術運算符在新類中沒有關閉。
from scipy.sparse import coo_matrix
import numpy as np
class Info(object):
def __init__(self, *arg, **args):
self.hello = "hello"
def say_hello(self):
print("hello")
class A(coo_matrix, Info):
def __init__(self, *arg, **args):
super(type(self), self).__init__(*arg, **args)
a = A(np.random.randint(2, size=(3,3)))
print("type of a: ",type(a))
a.say_hello()
b = 2*a
print("type of b: ",type(b))
如scipy.sparse.coo_matrix文檔中所述 ,它不直接支持算術運算。 顯然,如果您仍然嘗試進行算術運算,它將自動轉換為csr_matrix
。 這就是為什么您的b
不再是__main__.A
類型的原因。 但是,如果您改為直接繼承表單,例如csr_matrix
class A(csr_matrix, Info):
...
這具有正確的算術方法,因此無需轉換為另一種格式即可工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.