|
Original |
Translation |
|
60
|
The full list of supported assignment operators is ``+=``, ``-=``, ``*=``, ``/=``, ``%=``, ``**=``, ``&=``, ``|=``, ``^=``, ``>>=``, and ``<<=``. Python classes can override the augmented assignment operators by defining methods named :meth:`__iadd__`, :meth:`__isub__`, etc. For example, the following :class:`Number` class stores a number and supports using += to create a new instance with an incremented value.
|
|
|
61
|
class Number: def __init__(self, value): self.value = value def __iadd__(self, increment): return Number( self.value + increment) n = Number(5) n += 3 print n.value
|
|
|
62
|
The :meth:`__iadd__` special method is called with the value of the increment, and should return a new instance with an appropriately modified value; this return value is bound as the new value of the variable on the left-hand side.
|
|
|
63
|
Augmented assignment operators were first introduced in the C programming language, and most C-derived languages, such as :program:`awk`, C++, Java, Perl, and PHP also support them. The augmented assignment patch was implemented by Thomas Wouters.
|
|
|
64
|
|
65
|
Until now string-manipulation functionality was in the :mod:`string` module, which was usually a front-end for the :mod:`strop` module written in C. The addition of Unicode posed a difficulty for the :mod:`strop` module, because the functions would all need to be rewritten in order to accept either 8-bit or Unicode strings. For functions such as :func:`string.replace`, which takes 3 string arguments, that means eight possible permutations, and correspondingly complicated code.
|
|
|
66
|
Instead, Python 2.0 pushes the problem onto the string type, making string manipulation functionality available through methods on both 8-bit strings and Unicode strings. ::
|
|
|
67
|
>>> 'andrew'.capitalize() 'Andrew' >>> 'hostname'.replace('os', 'linux') 'hlinuxtname' >>> 'moshe'.find('sh') 2
|
|
|
68
|
One thing that hasn't changed, a noteworthy April Fools' joke notwithstanding, is that Python strings are immutable. Thus, the string methods return new strings, and do not modify the string on which they operate.
|
|
|
69
|
The old :mod:`string` module is still around for backwards compatibility, but it mostly acts as a front-end to the new string methods.
|
|