Overloaded Operators allowed???
Thomas Wouters
thomas at xs4all.net
Wed Jul 5 18:46:46 EDT 2000
On Wed, Jul 05, 2000 at 01:59:56PM -0700, Jeff wrote:
> Can you overload operators as you can in other languages? For example, can
> I make "&" give the address of something as in C++? Or can I only overload
> things like the cmp operator? i.e. I want to say &string and get the
> address of string.
Well, you have two issues here. There is no 'address-of' operator in Python,
so there is nothing to overload. Secondly, overloading in python is more
like overloading _behaviour_ than actually writing your own entirely
different operators. You can overload a number of operations, but you won't
be able to tell in what context they were called. For instance, if you
define a __pow__ overloader, it can be called by 'x ** y' or by 'pow(x,y)',
or by 'pow(x,y,z)'.
Also, because Python doesn't have augmented assignment (+=, >>=, etc) your
overloaders always have to return a new result object, instead of modifying
themselves in-place. So it's theoretically possible to make a file object
that takes arguments like the C++ I/O mechanisms:
x << "spam"
But because << is right-associative, you can't do something like:
x << "spam" << int(count) << "eggs"
unless you provide wrapper objects for all arguments that provide proper
__lshift__ methods ;-P As for augmented assignments, I've written a patch
for that, but it won't be going into Python for a while, if ever. See
http://www.xs4all.nl/~thomas/python/
This isn't really a problem, though, even in large programs: If what you
want to overload an operator with isn't really the same as the operator was
intended for, you shouldn't use an operator, you should use a method. I
remember how scared I was when I read about C++'s operator->*() ;-P
The 'special method names' are explained in the Language Reference:
http://www.python.org/doc/current/ref/specialnames.html
This includes operator overloading, indexing, etcetera. The part about the
methods that overload the usual operators is:
http://www.python.org/doc/current/ref/numeric-types.html
One thing that is missing from Python 1.5.2 is the ability to override the
'in' operator. That's added in Python 2.0 though, using __contains__. In
Python 1.5.2 and earlier, and in Python 2.0 when there is no __contains__
method, 'in' works by repeatedly calling '__getitem__'.
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list