Я создал свой собственный класс для матриц, и мне было интересно, как я могу использовать матрицу в качестве параметра функции, которая не должна получать матрицу?
например, вы можете использовать exp () для массива numpy. Как я мог скопировать это поведение? Я понял, что это как-то связано с iter и next (хотя, возможно, это неправильно)
Мой класс-
import random
from numbers import Number
class matrix:
def __init__(self, data):
self.data= data
self.rows= len(self.data)
self.cols= len(self.data[0])
def __str__(self):
output="["
for row in self.data:
output+=str(row)
if not row==self.data[-1]: output+=",\n"
output+="]"
return output
def __add__(self, other):
if isinstance(other, Number):
other = matrix([[other for i in range(self.cols)] for i in range(self.rows)])
if not isinstance(other, matrix):
raise Exception("Improper type to add")
if not self.rows == other.rows or not self.cols == other.cols:
raise Exception("Shapes do not match")
new_data=self.data.copy()
for i in range(len(new_data)):
for j in range(len(new_data[0])):
new_data[i][j]+=other.data[i][j]
return matrix(new_data)
def __sub__(self, other):
return self.__add__(other*(-1))
def __mul__(self, other):
if isinstance(other, Number):
data_copy= self.data.copy()
for row in data_copy:
for element in row:
element*=other
return matrix(data_copy)
if not isinstance(other, matrix):
raise Exception("Improper type to multiply")
if not self.cols== other.rows:
raise Exception("Cant multiply object of dimensions %d with object of dimensions %d" % self.shape() % other.shape())
new_data=[]
for i in range(self.rows):
new_data_row=[]
for j in range(other.cols):
temp_val=0
for h in range(self.cols):
temp_val+=self.data[i][h] * other.data[h][j]
new_data_row.append(temp_val)
new_data.append(new_data_row)
return matrix(new_data)
def shape(self):
return (self.rows, self.cols)
def random(rows, cols, val):
data = [[round(2*random.random()*val - val, 10) for i in range(cols)] for i in range(rows)]
output= matrix(data)
return output