7.6 原地运算符的优化
一般地,数值是不可变的。然而,数值运算符也被用于可变对象。例如list和set,对于一些扩展的赋值运算符来说,同样是支持的。作为一种优化方式,一个类中可包含一个运算符的原地运算版本,这些方法都为可变对象的赋值运算做了扩展。注意,这些方法最终都会以return self作为返回值,使得赋值运算更流畅。
方法 | 运算符 |
|---|---|
object. iadd (self, other) | += |
object. isub (self, other) | -= |
object. imul (self, other) | = |
object. itruediv (self, other) | /= |
object. ifloordiv (self, other) | //= |
object. imod (self, other) | %= |
object. ipow (self, other[, modulo]) | *= |
object. ilshift (self, other) | <<= |
object. irshift (self, other) | >>= |
object. iand (self, other) | &= |
object. ixor (self, other) | ^= |
object. ior (self, other) | |= |
由于FixedPoint对象是不可变的,因此我们不应对它们进行修改。除了这个例子以外,将看到有关原地运算符的一个更典型的应用。我们可以简单地为21点游戏中的Hand对象定义一些原地运算符。比如将如下定义加入Hand类中。
def iadd( self, aCard ):
self._cards.append( aCard )
return self
这样一来,就可以使用如下代码来完成发牌。
player_hand += deck.pop()
以上代码优雅地实现了手中牌的更新操作。
