Overloading =

Fredrik Lundh effbot at telia.com
Thu Feb 17 18:14:41 EST 2000


<jhefferon at my-deja.com> wrote:
 I have a class, rclass.  It has an attribute value.  Can I arrange
> so that the string
>     r1=r2
> sets r1.value to equal r2.value (where r1 and r2 are class instances,
> of course) without changing anything else about r1?  I'm willing to
> test, say, that r1.classtype==r2.classtype or something, first to make
> sure the assignment is sensible.

no.

> And if so, can I also have r1=7 set r1.value to be 7?

no.

...

the assignment statement binds names to objects, in
the current namespace.  the objects themselves aren't
involved in this.

assignment to container elements is another story -- it's
syntactical sugar for calls to setattr/setitem/setslice.

...

> I want to have a box in a GUI where users can enter code, such as
> assignments, and I'd like to avoid the reference to the underlying
> attribute.

you could perhaps evaluate that code in a custom name-
space (using the locals/globals argument to exec/eval),
and move data to and from attributes based on changes
in that namespace.

    d = {}
    for k, v in myobjects.items():
        d[k] = v.value
    exec code in d
    for k, v in d.items():
        try:
            myobjects[k].value = v
        except KeyError:
            raise NameError, k

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list