Witam
Mam problem z klasą macierzy liczb zespolonych.
Nie działa mi przeciążanie operatorów +,-,*.
Jak poprawnie to zrobić?
class zcomplex:
def __init__(self,real=1,imag=0):
self.real=real
self.imag=imag
def __repr__(self):
return f'<r:{self.real} i:{self.imag}>'
def display(self):
print(self)
class zmatrix:
def __init__(self, real=0 ,imag=0, rows=3):
self.rows=rows
self.tab=[[zcomplex(real,imag) for _ in range(rows)] for _ in range(self.rows)]
def __repr__(self):
return '\n'.join(' '.join(str(c) for c in self.tab[i]) for i in range(self.rows))
def display(self):
print(self)
def __add__(self,other):
tmp=zmatrix(self,0,0,rows)
for i in range(self.rows):
for j in range(self.rows):
tmp.tab[i][j]= self.tab[i][j] + other.tab[i][j]
return tmp
def __sub__(self,other):
tmp=zmatrix(self,0,0,rows)
for i in range(self.rows):
for j in range(self.rows):
tmp.tab[i][j]= self.tab[i][j] - other.tab[i][j]
return tmp
def __mul__(self,other):
tmp=zmatrix(self,0,0,rows)
for i in range(self.rows):
for j in range(self.rows):
for k in range(self.rows):
tmp.tab[i][j]+= self.tab[i][j] * other.tab[i][j]
return tmp
W przypadku gdy robię to w jednej klasie wszystko działa.
class zcomplex:
def __init__(self,rows,real,imag):
self.rows=rows
self.real=real
self.imag=imag
self.tab=[[complex(self.real,self.imag)]*self.rows for i in range(rows)]
def __add__(self,other):
tmp=zcomplex(self.rows,0,0)
for i in range(self.rows):
for j in range(self.rows):
tmp.tab[i][j]= self.tab[i][j] + other.tab[i][j]
return tmp
def __sub__(self,other):
tmp=zcomplex(self.rows,0,0)
for i in range(self.rows):
for j in range(self.rows):
tmp.tab[i][j]= self.tab[i][j] - other.tab[i][j]
return tmp
def __mul__(self,other):
tmp=zcomplex(self.rows,0,0)
for i in range(self.rows):
for j in range(self.rows):
for k in range(self.rows):
tmp.tab[i][j]+= self.tab[i][j] * other.tab[i][j]
return tmp
def prm(self):
for i in range(self.rows):
print(self.tab[i])
print('')