Operator overloading for part of an object

Alex Martelli aleaxit at yahoo.com
Wed May 23 12:19:31 EDT 2001


"David Humphrey" <dhumphrey at pdqdot.net> wrote in message
news:2C79DE2B4809FFC1.69C331B478CA7679.C3649C0080E44646 at lp.airnews.net...
    ...
> OK, I understand why it behaves this way, but I don't see how to preserve
> c.name while updating c.data with the computed value.  I konw I need to
> overload the '=' operator, but don't see facilities in python to do that.

There is no way in Python to change the meaning of '=',
which is not an operator, but rather a separator (in
various contexts including plain assignment).

When you use plain assignment to re-bind a local or
global variable (as opposed to re-binding an attribute
or item or slice of some object), the re-binding will
happen -- period.  The object previously bound to
that variable name is NEVER affected in any way (save
that it disappears if/when there are no references to
it any more, by garbage-collection).

There is no way you can change this.
    c = a + b
will ALWAYS rebind variable c, NEVER affect whatever
c was previously bound to.

So, you need to use different syntax sugar for the
functionality you desire.  There is an abundance
of forms -- for example, if all the references in
question were attributes on some supervising object
rather than local or global variables, __setattr__
of the supervising object would give you the chance
to do the dark deed you desire.  But you can't use
plain assignment's syntax-sugar on variables for
other purposes than plain assignment - i.e., to
bind or re-bind those variables.


Alex






More information about the Python-list mailing list