[英]How to modify arithmetic operators (+,-,x)
我目前正在编写适用于Python 3.x的线性代数模块,其中涉及自定义矩阵对象。
有什么方法可以使+,-,*等基本算术运算符遵守我的矩阵对象? 例如 -
>>> A = matrix("1 2;3 4")
>>> B = matrix("1 0; 0 1")
>>> A + B
[2 2]
[3 5]
>>> A * A
[7 10]
[15 22]
现在,我已经编写了用于加法,乘法等的单独函数,但是键入A.multiply(A)
比简单地A*A
麻烦得多。
另外,当您尝试实现矩阵并且矩阵是容器时,可能会发现为您的类型定义自定义容器方法很有用。
更新:这是使用特殊方法实现算术运算符的自定义对象的示例:
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
除非您是专门为学习或练习而设计的,否则应查看数值python numpy,这是基本线性代数和矩阵的事实上的标准解决方案。 它有一个矩阵类,它可以满足您的需求。
class matrix:
def __init__(self, string_matrix):
self.matrix = string_matrix.split(";")
for i in range(len(self.matrix)):
self.matrix[i] = map(int, self.matrix[i].split())
def __add__(self, other):
return_matrix = [[i for i in row] for row in self.matrix]
for i in range(len(self.matrix)):
for j in range(len(self.matrix[i])):
return_matrix[i][j] = self.matrix[i][j] + other.matrix[i][j]
return list_to_matrix(return_matrix)
def __str__(self):
return repr(self.matrix)
def list_to_matrix(list_matrix):
string_form = ""
for row in list_matrix:
for item in row:
if (item != row[-1]): string_form += str(item) + " "
else: string_form += str(item)
if (row != list_matrix[-1]): string_form += ";"
return matrix(string_form)
您可能希望包括几项检查(例如添加不同维度的矩阵,或将矩阵添加到非矩阵的对象等),但这只是一个简单的示例。 还要注意,我正在使用list_to_matrix()
函数返回一个matrix
对象-如果这不是所需的功能,则可以很容易地对其进行更改。 您需要对所有其他算术函数使用类似的过程。
输出:
>>> a = matrix("3 4;1 4")
>>> b = matrix("2 3;0 0")
>>> print(a)
[[3, 4], [1, 4]]
>>> print(b)
[[2, 3], [0, 0]]
>>> print(a + b)
[[5, 7], [1, 4]]
正如在其他答案之一中提到的那样, numpy可能是用于矩阵运算的好资源-许多此功能已经内置。
>>> import numpy as np
>>> a = np.matrix("3 4;1 4")
>>> b = np.matrix("2 3;0 0")
>>> print(a)
[[3 4]
[1 4]]
>>> print(b)
[[2 3]
[0 0]]
>>> print(a + b)
[[5 7]
[1 4]]
如果您在类中定义了一些特殊的方法 ,Python将调用它们进行算术运算。 定义加,乘,除和减的示例类:
class motar:
def __add__(self, other): return "9999"
def __mul__(self, other): return "8888"
def __sub__(self, other): return "7777"
def __div__(self, other): return "6666"
m = [ motar() for x in range(2) ] # create two instances
# arithmetic operations on class instances will call
# ... the special methods defined above:
print m[0] + m[1]
print m[0] * m[1]
print m[0] - m[1]
print m[0] / m[1]
给出:
9999
8888
7777
6666
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.