3.3.7 结合操作符和定制类
operator模块中的函数完成操作时会使用标准python接口,所以它们不仅适用于内置类型,也适用于用户定义的类。
from operator import *
class MyObj:
"""Example for operator overloading"""
def __init__(self,val):
super(MyObj,self).__init__()
self.val =val
def __str__(self):
return 'MyObj({})'.format(self.val)
def __lt__(self,other):
"""com[are for less-than"""
print('Testing {} < {}'.format(self,other))
return self.val < other.val
def __add__(self,other):
"""aadd values"""
print('Adding {} + {}'.format(self,other))
return MyObj(self.val + other.val)
a = MyObj(1)
b = MyObj(2)
print('Comparison:')
print(lt(a,b))
print('\nArithmetic:')
print(add(a,b))
要全面了解每个操作符使用的所有特殊方法,请参见python参考指南。
运行结果: