Overloading =
Ken Seehof
kens at sightreader.com
Sun Feb 27 18:43:39 EST 2000
You can't overload "=" in that case, because "=" is not an assignment
operator. In fact, "=" is not an operator at all (in this case). It binds
a
name to an object. The statement "a=5" doesn't even look at what
kind of thing the name "a" used to refer to, it simply binds the name "a"
to the object 5.
Here a useful exception to the rule:
In the statement
obj.a = 5
the "=" is the __setattr__ operator, so it's equivalent to
obj.__setattr__('a', 5)
Then you overload __setattr__ to do whatever typechecking and stuff you
want.
Perhaps you could prefix the users string with "obj." so "a=5" becomes
"obj.a=5".
You almost certainly want "a" to be a member of an object anyway. I'd
probably nuke the ".value" idea, unless you need it for something, though
you
could make __setattr__ do anything you want including "obj.a.value=5".
Overall, I'd say you've suffered too long as a C++ programmer (as I have)
and you need to forget everything you've ever learned. Take a vacation.
When you get back, start again on python with a fresh mind. If you try
to get python to do C++ tricks, you will just make your life difficult.
Python's
got its own stuff thats way better.
Felix Thibault wrote:
> At 22:47 2/17/00 GMT, 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.
> >
> >And if so, can I also have r1=7 set r1.value to be 7?
> >
> >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.
> >
> >Thanks,
> >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
> >
> >
>
> Would it be OK for this assignment to use another operation ?
> You could use something like-
>
> def __lshift__(self, other):
> if hasattr(other, 'value'):
> self.value = other.value
> else:
> self.value = other
>
> then your users could type r1 << r2 to put the value of r2 into r1.
>
> -Felix
More information about the Python-list
mailing list