Overloading assignment operator
Carroll, Barry
Barry.Carroll at psc.com
Tue Jan 23 18:32:34 EST 2007
> -----Original Message-----
> From: Achim Domma [mailto:domma at procoders.net]
> Sent: Tuesday, January 23, 2007 10:25 AM
> To: python-list at python.org
> Subject: Overloading assignment operator
>
> Hi,
>
> I want to use Python to script some formulas in my application. The
user
> should be able to write something like
>
> A = B * C
>
> where A,B,C are instances of some wrapper classes. Overloading * is no
> problem but I cannot overload the assignment of A. I understand that
> this is due to the nature of Python, but is there a trick to work
around
> this?
> All I'm interested in is a clean syntax to script my app. Any ideas
are
> very welcome.
>
> regards,
> Achim
Hello, Achim,
I asked this question (in a different context) some months ago on the
Python tutor mailing list (tutor at python.org). The answer I got is
summarized below.
** There is no assignment operator in Python, assignment is a
** binding of an object to a name.
(Alan Gauld)
* ... the assignment operator is used to assign an
* object to a name in the current namespace... IOW, you cannot "overload
* the assignment operator."
(wesley chun)
Mr. Chun went on to describe a way to accomplish something similar,
using properties. I reprint it here, slightly rewritten to match your
use case.
* ...here is where
* properties become useful. you can create a getter, setter, and even a
* deleter and doc string if you want. here's how you use it... add the
* following to your class:
* def get_result(self):
* return self.__result
*
* def set_result (self, expression):
* self.__result = expression
*
* result = property(get_result, set_ result, doc='result of operations')
*
* -----
*
* in actuality, the value is stored in self.__result, but access is via
* self.result. this should give you what you need provided you are
happy
* with using "A.result = B * C" vs. "A = B * C", the latter of which
* will never work the way you want. ...
I have tested this using the admittedly simple-minded code snipped
below.
>>>>>>>>>>
@BCARROLL[Python]|3> class Aclass:
|.> def __init__(self):
|.> __result = None
|.> def get_result(self):
|.> return self.__result
|.> def set_result (self, result):
|.> self.__result = result
|.> result = property(get_result, set_result,
doc='result of expression')
|.>
@BCARROLL[Python]|5> A = Aclass()
@BCARROLL[Python]|7> a.result = 2*3
@BCARROLL[Python]|8> a.result
<8> 6
@BCARROLL[Python]|9> a.result = 25.0 * 5.25
@BCARROLL[Python]|10> a.result
<10> 131.25
@BCARROLL[Python]|11>
>>>>>>>>>>
HTH
Regards,
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
More information about the Python-list
mailing list