Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# это пример показывает применение __matmul__ и __imatmul__ для пользовательских классов
class MyMatrix:
def __init__(self, data):
self.data = data
# для получения элементов матрицы как A[строка, столбец]
def __getitem__(self, pos):
i, j = pos
return self.data[i][j]
# реализует оператор @ для нашей MyMatrix
def __matmul__(self, B: 'MyMatrix'):
A = self
b_rows = len(B.data)
b_cols = len(B.data[0])
a_rows = len(A.data)
data = [[sum(A[i, k] * B[k, j] for k in range(b_rows)) for j in range(b_cols)] for i in range(a_rows)]
return MyMatrix(data)
# добавим также оператор @=
def __imatmul__(self, other):
self.data = (self @ other).data
return self
# для печати
def __str__(self):
return str(self.data)
print('-' * 20, 'MY MATRIX DEMO', '-' * 20)
a = MyMatrix([
[1, 2],
[3, 4]
])
print("a =", a)
b = MyMatrix([
[5, 0],
[-1, 3]
])
print("b =", b)
b @= MyMatrix([
[-1, 0],
[0, -1]
])
print("b @ (-E) =", b)
print("a @ b =", a @ b)
# проверим правильность через numpy
print('-' * 20, 'NUMPY', '-' * 20)
import numpy as np
a = np.array([
[1, 2],
[3, 4]
])
print("a =", a.tolist())
b = np.array([
[5, 0],
[-1, 3]
])
print("b =", b.tolist())
e = np.eye(2, dtype=int)
# numpy не поддерживает @=
try:
b @= -e
except TypeError as t:
print(t)
b = b @ -e
print("b @ (-E) =", b.tolist())
print("a @ b =", (a @ b).tolist())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.