I am currently writing a Linear Algebra module for Python 3.x wherein I deal with self-defined matrix objects.
Is there any way I can make the basic arithmetic operators like +, -, * adhere to my matrix objects? For example -
>>> A = matrix("1 2;3 4")
>>> B = matrix("1 0; 0 1")
>>> A + B
[2 2]
[3 5]
>>> A * A
[7 10]
[15 22]
Right now I have written separate functions for addition, multiplication, etc. but typing A.multiply(A)
is much more cumbersome than simply A*A
.
You are looking for special methods. Particularly at emulating numerical types section.
Also, as you're trying to implement matrices and matrices are containers, you may find useful to define custom container methods for your type.
UPDATE: Here is an example of custom objects using special methods to implement arithmetical operators:
class Value(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
if not isinstance(other, Value):
raise TypeError
return Value(self.x + other.x)
def __mul__(self, other):
if not isinstance(other, Value):
raise TypeError
return Value(self.x * other.x)
assert (Value(2) + Value(3)).x == 5
assert (Value(2) * Value(3)).x == 6
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments