繁体   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