简体   繁体   English

为什么NumPy中的矩阵乘法不调用__add__方法?

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

How does the method __mul__ in the class matrix in NumPy work? NumPy中的class matrix中的方法__mul__是如何工作的呢? I want to implement a binary matrix multiplication, and I have a class Binary :我想实现二进制矩阵乘法,我有一个 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

My test:我的测试:

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)

Result:结果:

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

The method __add__ is not used.不使用方法__add__ Whereas there is a summation in matrix multiplication.而矩阵乘法中有求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM