+ 1

Is it possible to create method for 2 different classes? How?

So for example I have 2 classes named Matrix and Vector. Matrix's instance attribute is 2D list and Vector's instance attribute is 1D list. The list contain floating point. So it's like: class Matrix: dim = 2 def __init__(self,A): self.Mat=A def __mul__(self,other): #here is process to multiple Matrix with Vector class Vector: def __init__(self,V): self.Vec=V How to write the program in __mul__ method? Should I create __mul__ method in class Vector too?

27th Jun 2017, 2:12 PM
Ahmad Fahadh Ilyas
Ahmad Fahadh Ilyas - avatar
4 Respuestas
+ 2
try this, __rmul__=__mul__ in matrix class
27th Jun 2017, 5:53 PM
kars
kars - avatar
+ 1
Can you create a shared method between the two Classes? Yes, you can. Inheritance is one of the principles of OOP and is extremely helpful (also can be extremely dangerous). If you wanted your Vector class to have the same method (inherit) as your Matrix class you should signify that it's inheriting from class Matrix... class Vector(Matrix): def __init__(self, v): self.vec = v
27th Jun 2017, 2:35 PM
Don
Don - avatar
+ 1
@Don no, that's not what I mean. What I mean is... how to fill the __mull__ method so when I write A=Matrix([[1,2],[3,4]]) x=Vector([1,2]) Ax=A*x #Ax is instance from class Vector print(Ax.Vec) the output is [5,11]
27th Jun 2017, 2:40 PM
Ahmad Fahadh Ilyas
Ahmad Fahadh Ilyas - avatar
0
Well, I tried to look into it for you but solutions are slightly tedious if you're trying to hard code it. You can look into third party libraries like numpy that makes the usage of matrixes and vectors easier.
27th Jun 2017, 3:33 PM
Don
Don - avatar