Skip to content

Instantly share code, notes, and snippets.

@tirinox
Created February 16, 2019 09:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tirinox/d489a6b320b92dbb344d36c046a3529d to your computer and use it in GitHub Desktop.
Save tirinox/d489a6b320b92dbb344d36c046a3529d to your computer and use it in GitHub Desktop.
# это пример показывает применение __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