How do I overload 'equals'?

Mirko Zeibig mirko-lists at zeibig.net
Mon Feb 2 06:36:06 EST 2004


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

Regards
Mirko
-- 



More information about the Python-list mailing list