harold.fellermann at upf.edu
Mon Jun 13 16:36:36 CEST 2005
On 13.06.2005, at 15:52, Xavier Décoret wrote:
> I would like to know if there is for python's classes an equivalent of
> the operator= that can be overidden.
> Let's say I have
> and I want to write
> and I want this to change some internal value of a instead of making a
> point to a new object (an int 5)
> In other word, I would like to be able to use a=5 instead of a.set(5)
> Is that possible?
the short answer is: no.
the long answer:
if you write
an instance of class A is created and bound to the local identifier
'a'. If you later write
the object 5 is reassigned to the same identifier, deleting whatever
value was stored there before. The identifier itself does not impose
any restrictions on the type of instances that can be bound to it.
Binding an instance of class A in the first part, does not make the
identifier of the kind 'can-only-bind-A-instances'. In other words:
identifiers don't have types. Thus, there is no mechanism that allows
to change the binding behavior of identifiers.
As a general advise, don't try to write C++ in python. I think, for
most cases, there are far better solutions than changing the assign
operator anyway... explicit is better than implicit:
If class A has only one dedicate value and no internal state, make it a
Otherwise, it is worth mentioning the name of the member to set.
IMHO this increases the readability of your source code:
- harold -
"I was born not knowing
and have had only a little time
to change that here and there."
-- Richard Feynman
More information about the Python-list