operator overloading + - / * = etc...
steve at REMOVE.THIS.cybersource.com.au
Sun Oct 8 03:08:10 CEST 2006
On Sat, 07 Oct 2006 17:21:55 -0500, Tim Chase wrote:
>>> With the caveat of the "=" mentioned in the subject-line (being
>>> different from "==")...I haven't found any way to override
>>> assignment in the general case.
>> Why would you want to do that?
> For the same reason one would use property() to create
> getter/setter functions for a particular variable--to intercept
> attempts to set a variable.
Despite sloppy talk to the contrary (which I think most of us do from time
to time), Python doesn't have variables. It has names and objects. Names
are just labels -- there is no difference in behavior between the *names*
this_is_an_integer and this_is_a_string. (The *objects* they point to are
a different story, naturally.)
Objects do not, and can not, know what names they are bound to, nor can
they tell when the name or names they are bound to changes. Objects just
don't care what names they are bound to -- in fact, many objects aren't
bound to any name at all.
Suppose we bind the name "x" to the object 1, and then rebind the name "x"
to the object . Which object's hypothetical __assign__ method should get
called? Object 1 or object ? Both of them? In what order? Why should
the empty list care what names it is bound to?
> I'm not sure there's an elegant way
> to do it other than creating a custom container object with a
> getter/setter using property().
You shouldn't be programming C++ in Python, you should rethink how you
are solving the problem.
But having done that, if you still find that the property() idiom makes
sense for names/objects, you can get close if you are willing to write x =
1 as NAMESPACE.x = 1, and then use a custom class or module to implement
the behavior you want.
Here is one module that you might be able to use:
More information about the Python-list