Overloading assignment operator
J. Clifford Dyer
webmaster at cacradicalgrace.org
Mon Jan 29 17:22:01 EST 2007
Steven D'Aprano wrote:
> On Tue, 23 Jan 2007 18:07:55 -0800, Russ wrote:
>
>> Achim Domma wrote:
>>> 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
>> Why do you need to overload assignment anyway? If you overloaded "*"
>> properly, it should return
>> the result you want, which you then "assign" to A as usual. Maybe I'm
>> missing something.
>
> One common reason for overriding assignment is so the left-hand-side of
> the assignment can choose the result type. E.g. if Cheddar, Swiss and
> Wensleydale are three custom classes, mutually compatible for
> multiplication:
>
> B = Cheddar() # B is type Cheddar
> C = Swiss() # C is type Swiss
> # without overloading assignment
> A = B * C # A is (possibly) Cheddar since B.__mul__ is called first
> A = C * B # A is (possibly) Swiss since C.__mul__ is called first
> # with (hypothetical) assignment overloading
> A = B * C # A is type Wensleydale since A.__assign__ is called
>
> Except, of course, there is no assignment overloading in Python. There
> can't be, because A may not exist when the assignment is performed, and
> if it does exist it might be a complete different type.
>
> Instead, you can do something like this:
>
> A = Wensleydale(B) * Wensleydale(C)
>
> or
>
> A = Wensleydale(B * C)
>
>
>
>
I think that's the first time I've actually seen someone use a Monty
Python theme for a python example, and I must say, I like it. However,
"We are all out of Wensleydale."
Cheers,
Cliff
More information about the Python-list
mailing list