How to deal __getattr__

bruno modulix onurb at xiludom.gro
Sun Oct 17 13:26:35 EDT 2004


limodou a écrit :
(please don't top-post -- fixed)

> On Sat, 16 Oct 2004 13:59:11 +0800, limodou <limodou at gmail.com> wrote:
> 
>>I found it puzzled me that:
>>
>>class A:
>>   def __getattr__(self, name):
>>       return None
>>a=A()
>>b=A()
>>a==b will raise Exception:
>>
>>__eq__
>>
>>Traceback (most recent call last):
>> File "<pyshell#7>", line 1, in -toplevel-
>>   a==b
>>TypeError: 'NoneType' object is not callable
>>
>>I want to compare the objects themself not the attributes of them. 
(snip)
>>
 > I resolved the problem via defining __eq__method, just like:
 >
 >>>>class A:
 >
 > 	def __getattr__(self, name):
 > 		print name
 > 		return None
 > 	def __eq__(self, obj):
 > 		return id(self) == id(obj)
 >
 >
 >>>>a=A()
 >>>>b=A()
 >>>>a==b
 >
 > False
 >
 > I don't know whether it's the right solution, any ideas?

You've already got the answer, thanks to Andrew Dalke.

Now I may be wrong, but it seems that you are confusing equality and 
identity. The first is about testing if two objects have the same value, 
the second about knowing if two symbols are bound to the same object. 
There may of course be cases where the two concepts overlaps, and the 
default behavior for equality test is to test identity -- which is quite 
sensible since the language can't guess the semantic of your objects !-).

If you want to test for identity (ie 'are symbols foo and bar bound to 
the same object), the operator to use is 'is' :

class Foo:
     def __init__(self, name):
         self.name = name
foo = Foo('baaz')
bar = Foo('baaz')
a is b
->False

The __eq__ magic method should be used to override default 'identity as 
equality' behavior by providing your own value test:

class Bak(Foo):
     def __eq__(self, other):
         if hasattr(other, name):
             return self.name == other.name
         else:
             return False
bak = Bak('baaz')
bak == foo
->True
bak == bar
->True
bak is bar
->False

You may want to have a look at the fine manual, here
http://docs.python.org/ref/comparisons.html
and here
http://docs.python.org/ref/customization.html

(please someone correct me if I said any stupiditie)

Bruno



More information about the Python-list mailing list