overriding '=' operator?

U

user

Hi,

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

Thanks,

Toby
 
E

Erik Max Francis

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

You can in statements like

a = something

or

a.x = something

by overriding methods on the a object, but you cannot override the
behavior for

a = something
 
J

John Roth

Hi,

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

No, because "=" isn't an operator, it's a statement.

John Roth
 
S

Stephen Horne

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'.
 
T

Terry Reedy

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

In Python, = is *not* an operator. It is more like a statement
keyword.

tjr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top