
上QQ阅读APP看书,第一时间看更新
6.6 重载运算符
6.5节讲述的类的内置方法中,有许多是用来替换运算符的功能,这种特性称为重载运算符(overloading operator)。例如:
(1)__add__(a, b)方法等于a + b。
(2)__sub__(a, b)方法等于a - b。
(3)__mul__(a, b)方法等于a * b。
(4)__ mod__(a, b)方法等于a % b。
要在Python解释器内使用这些运算符函数,首先必须加载operator模块,然后调用operator模块的运算符函数。例如:
>>> import operator >>> operator.add(12, 20) 32
表6-1列出这些重载运算符及其与功能相同的内置函数名称对照。
表6-1 重载运算符与内置函数对照
