+= overloading?
Don O'Donnell
donod at home.com
Sun Jun 17 02:40:22 EDT 2001
Neil Macneale wrote:
>
> I am creating a colored stringbuffer class, and I want to append words to
> the buffer with the '+=' operator. Ex:
>
> >>>csb = CSB("INIT STRING")
> >>>csb += "Hello"
> >>>print csb
> INIT STRINGHello
>
> would be the desired effect. I can't seem to find anything in the lib
> docs about overloading that operator though. Am I looking in the wrong
> place? It is also important that a new object is NOT created every time
> the operator is used, because that would be a waste.
>
> Suggestions? Thanks for any tips!
>
> Neil Macneale
>
> --
> To reply to me via email, remove the '-devnull' from my address.
It's in the Reference Manual, section 3.3.6 in Release 2.1, not the
Lib docs, since it's an operator defined by the language, not the
library.
The method you're looking for is called augmented addition, and it
is defined as:
def __iadd__(self, other):
...
return self
In general, the augmented arithmetic operators should update self
in place where possible. In the case where self is immutable, as
yours may be since it's string based, you'll have to create a new
concatenated string and rebind self to it. These methods must also
return self, since just rebinding the local copy of the self ref
will never be seen by the caller.
Good luck.
-Don
More information about the Python-list
mailing list