How do I overload 'equals'?

James Henderson james at logicalprogression.net
Mon Feb 2 06:59:35 EST 2004


On Monday 02 February 2004 11:36 am, Mirko Zeibig wrote:
> Equis Uno said the following on 02/02/2004 11:52 AM:
> > Hi there,
> >
> > I just figured out how to use __add__() to overload the "+" operator
> > for objects of a class.
> >
> > According to googel queries, I see other functions available to me for
> > overloading other operators:
> >
> > __mul__(), __sub__(), ...
> >
> > I was hoping to overload "=" or use some string to do assignment with
> > side effects.
> >
> > For example,
> >
> > obj1 = ClassX('green')
> > obj2 = ClassX('red')
> >
> > obj1 superEqual obj2
> >
> > I'd like to be able to control the behavior of the superEqual operator
> > such that it does assignment with side effects.
> >
> > For example, maybe it would do this:
> >
> > obj = obj2
> > incrementEqualityCounter()
> > addAuditRecordToDB()
> >
> > How do I do this in Python?
>
> Overloading operators is explained in
> http://python.org/doc/2.3.3/lib/module-operator.html#l2h-490
>
> Maybe you are looking for __eq__? After overloading it, you may
> say:
> if obj1 == obj2:
>    ...
>  From what you wrote I think you want to overload the assign operator
> (single =) . This is not supported in Python directly, but you may take
> a look at descriptors:
> http://users.rcn.com/python/download/Descriptor.htm

Descriptors, or just defining good old fashioned __getattr__ 
(http://www.python.org/doc/current/ref/attribute-access.html), can only 
overload assignment to attributes.

Changing the meaning of "=", as I believe you want to do, is the kind of 
change to the syntax of the language that Python by design does not allow in 
order to maintain consistency across different people's code (and no doubt 
for lots of other good reasons).  If you really want to do this perhaps you'd 
be better off using Io <wink>.  Otherwise you'll have to settle for defining 
a function "superEqual" (or better "superAssign", since"=" is an assignment 
operator not an equality operator.)

James
-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list