与乘法重定义相关的方法有两个,一个是 mul ,另一个是 rmul 。 你可以在类中定义其中的一个,也可以两个都定义。
如果乘法操作符“*”的左右操作数都是用户定义的数据类型,那么 调用 mul 。若左边的操作数是原始数据类型,而右边是用户定义数据类 型,则调用 rmul 。
请看例子:
class Line:
def __init__(self, length = 0.0):
self.length = length
def __str__(self):
return str(self.length)
def __mul__(self, other): #乘法重定义
return Rect(self.length, other.length)
def __rmul__(self, other): #乘法重定义
return Line(self.length * other)
class Rect:
def __init__(self, width = 0.0, length = 0.0):
self.width = width
self.length = length
def __str__(self):
return ’(’ + str(self.length) + ’,’
+ str(self.width) + ’)’
def area(self): #计算长方形的面积
return self.width * self.length
在这个例子中,定义了Line(线类)和Rect(长方形类)。重定义了Line类的乘法操作符。第一个重定义表示两个线实例相乘,得到并返回长方形实例。第二个重定义表示一个线实例乘以一个原始数据类型,得到并返回一 个线实例。执行结果如下:
>>> aline = Line(5.87)
>>> bline = 2.9 * Line(8.34)
>>> print ’aline = ’ , aline, ’bline = ’,bline
aline = 5.87 bline = 24.186
>>> rect = aline * bline
>>> print rect
(24.186,5.87)
>>> print rect.area()
141.97182
乘法重定义的第二种形式,必须严格按照“2.9 * Line(8.34)”的书写 顺序,要是调换一下顺序,解释器将给出错误信息。
>>> bline = Line(8.34) * 2.9
AttributeError: ’float’ object has no attribute ’length’
上一篇:《Python学习笔记》第十三章
下一篇:《Python学习笔记》第十四章