Controlling assignation

Peter Hansen peter at
Mon Jun 13 16:17:01 CEST 2005

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
>  >>> a=A()
> and I want to write
>  >>> a=5
> 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?

Not with simple names, such as "a".  You can do it if you assign to an 
attribute of an object, such as a.b, by intercepting the assignment call 
via __setattr__ or a property.

In Python, anyone reading your code would expect that "a=5" represents a 
rebinding of the name "a" to a new object, possibly destroying the old 
object, and if you did manage to subvert that you'd just be making your 
code unreadable, in the way that overuse of #define to change syntax in 
C can make C code (even more) unreadable.  Please reconsider why you 
want to do that and find a more conventional approach, such as a.set(5).


More information about the Python-list mailing list