簡體   English   中英

為什么NumPy中的矩陣乘法不調用__add__方法?

[英]Why does matrix multiplication in NumPy not call the __add__ method?

NumPy中的class matrix中的方法__mul__是如何工作的呢? 我想實現二進制矩陣乘法,我有一個 class Binary

class Binary(int):
    def __init__(self, val):
        if val != 0:
            self.val = 1
        else:
            self.val = 0

    def __add__(self, other):
        print('add')
        return self.val ^ other

    def __radd__(self, other):
        print('radd')
        return self.val ^ other

我的測試:

from Binary import Binary
from numpy import matrix

i = Binary(1)
o = Binary(0)
a = matrix([i, i, o, i, i, o, o], dtype=Binary)
b = matrix([[o, o, i],
           [o, i, o],
           [o, i, i],
           [i, o, o],
           [i, o, i],
           [i, i, o],
           [i, i, i]], dtype=Binary)
print(a * b)

結果:

./test.py
[[2 1 2]]

不使用方法__add__ 而矩陣乘法中有求和。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM