overriding '=' operator?

Stephen Horne steve at ninereeds.fsnet.co.uk
Thu Oct 30 20:42:02 EST 2003


On Thu, 30 Oct 2003 20:32:52 GMT, user at domain.invalid wrote:

>Hi,
>
>Is it possible to override assignment, the
>way that '+' can be overridden for example?

No, not for the simple 'variable = value' case, because '=' doesn't
modify a value.

In Python, assignment binds the RHS value to the LHS name. The type of
the previous LHS value is irrelevant - in Python, the type is a
property of the value rather than the variable.

The object previously bound to that variable is unaffected (apart from
reference counting and possible garbage collection) and isn't really
involved in the assignment. And as it isn't involved, it makes no
sense for it to define what the assignment operator does.

In short, you should think of the assignment operator as assigning to
the variable - not to whatever object that variable happened to be
bound to before the assignment.

This is, of course, very different to statically typed languages like
Ada and C++ where it makes sense for the assignment operator to be
overridden based on the type - the type being associated with the
variable, in these cases, rather than the value that happens to be
stored there.

If you really want to override assignment, one way would be to define
a property. Instead of 'var = value' you would then write
'var.propertyname = value'. Using a property, assignments are
translated into calls to getter or setter methods, which can be
overridden fairly easily, and which can modify the object 'in place'.


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list