13.13 用特殊方法定制类
特殊方法允许类通过重载标准操作符+,*,甚至包括分段下标及映射操作[]来模拟标准类型。如同其他很多保留标识符,这些方法都是以双下划线(__)开始及结尾的。
13.13.1 简单定制(RoundFloat2)
>>> class RoundFloatManual(object): ... def __init__(self, val): ... assert isinstance(val, float), "value must be a float!" ... self.value = val ... def __str__(self): ... return '%.2f'%self.value ... def __repr__(self): ... return self.__str__() ... >>> value = RoundFloatManual(12.0) >>> value 12.00 >>> print value 12.00 >>> RoundFloatManual(10) Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<interactive input>", line 3, in __init__ AssertionError: value must be a float! >>>
13.13.2 数值定制(Time60)
>>> class Time60(object): ... def __init__(self, hr, min): ... self.hr = hr ... self.min = min ... def __str__(self): ... return '%d:%d'%(self.hr, self.min) ... def __add__(self, other): ... return self.__class__(self.hr + other.hr, self.min + other.min) ... def __iadd__(self, other): ... self.hr += other.hr ... self.min += other.min ... return self ... __repr__ = __str__ ... >>> time = Time60(10, 20) >>> time 10:20 >>> print time 10:20 >>> time + Time60(11,10) 21:30 >>> time += Time60(1,0) >>> time 11:20 >>>
像加号(+),我们只需要重载__add__()方法。__iadd__()是用来支持像mon+=tue 这样的操作符,并把正确的结果赋给mon。重载一个__i*__()方法的唯一秘密就是它必须返回self。