Overloading =

bjorn bjorn at roguewave.com
Fri Feb 18 13:39:11 EST 2000


How about making register an object.  Then you can do:

    register[r1] = 7
    register[r2] = memory[register[r1]]  # indirect load?
    etc.

and the implement __getitem__ and __setitem__ to do your magic.

--bjorn
(ps: assuming r1 = 'r1' or something similar...)

jhefferon at my-deja.com wrote:

> In article <m3bt5fo1lk.fsf at atrus.jesus.cam.ac.uk>,
>   Michael Hudson <mwh21 at cam.ac.uk> wrote:
> > jhefferon at my-deja.com writes:
> >
> > > 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?
> >
> > No. Assignment rebinds references, rather than affecting objects. This
> > is quite a difference from C++ (say), probably one of the harder ones
> > to get one's head around.
> >
> > >
> > > And if so, can I also have r1=7 set r1.value to be 7?
> > >
> > Hmm... do you know about the "exec <blah> in globals,locals" style of
> > doing things? Though `exec'ing user input sounds deeply unwise to me.
> > What is it you are trying to do? Maybe we can come up with a better
> > solution (no promises though).
>
> Thanks.  I *am* reluctant to allow students to accidently exec something
> that erases all files, or something.
>
> I am simulating a computer.  It is made up of registers and each
> register (memory or CPU) may have more than one attribute (for instance,
> whether to print it out in binary or hex, or how many times it has
> been referenced in this program, or what source line compiled to this
> register, etc.).  That's why each register is a class instance rather
> than a simple variable.
>
> I want to have the obvious GUI, that allows a person to scroll through
> memory, for instance.  I also want to allow them to do things like
> set a register `rA=7' or `rA=memory[52]'.
>
> In the register class I can use __setattr__ to let me write either
>   `rA.value=7' or `rA.value=memory[52]',
> right (I look at the type of the thing on the right and if it is a
> class instance then I see if, say, memory[52].classtype==``register'')?
> But I can't eliminate the `.value' on the left?  I thought maybe I could
> mess with the top-level dictionary (I don't know what I mean by that!).
>
> Thanks again,
> Jim Hefferon jim at joshua.smcvt.edu
>
> Sent via Deja.com http://www.deja.com/
> Before you buy.
> --
> http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list