__getattr__ and __cmp__

William Park parkw at better.net
Thu Oct 5 04:18:38 EDT 2000


On Wed, Oct 04, 2000 at 07:51:58PM -0700, Michel Sanner wrote:
> Hi,
> 
> This is using Python 1.5.2 under IRIX6.5
> 
> Could anyone tell me how to specialize __getattr__ without loosing default
> instance comparison ?
> 
> here is what the problem is:
> 
> class A:
>   def __init__(self):
>       self.val=1
> 
> a1= A()
> a2= A()
> 
> a1==a2 returns 0
> a1==a1 returns 1 as expected
> 
> now when I add __getattr__
> 
> >>> class A:
> ...   def __init__(self):
> ...       self.value=1
> ...   def __getattr__(self, val):
> ...       if val[:2]=='__':
> ...          return self.__dict__[val]
> ...       elif val=='value':
> ...          print 'Sorry val is invisible'
> 
> >>> a1
> getattr for : __repr__
> <__main__.A instance at 100d4a90>
> >>> a1.value
> 1   ##### __getattr__ does not get call ???

You should know that __getattr__ is called only when the attribute is not
defined.  So, a1.value does exist as a variable of instance.


> >>> a1 == a2
> getattr for : __coerce__
> getattr for : __cmp__
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
>   File "tstcmp.py", line 8, in __getattr__
>     return self.__dict__[member]
> KeyError: __cmp__

Without __getattr__, you are comparing memory address of 'a1' and 'a2'.  But,
with __getattr__, it now looks for __cmp__ which you have not defined.

So, try defining __cmp__ method.

> 
> I do not find the default object comparison any longer !
> 
> could anyone tell me what is happening ?
> 
> Thanks for any help
> 
> -Michel
> 
> -- 
> 
> -----------------------------------------------------------------------
> 
> >>>>>>>>>> AREA CODE CHANGE <<<<<<<<< we are now 858 !!!!!!!
> 
> Michel F. Sanner Ph.D.                   The Scripps Research Institute
> Assistant Professor			Department of Molecular Biology
> 					  10550 North Torrey Pines Road
> Tel. (858) 784-2341				     La Jolla, CA 92037
> Fax. (858) 784-2860
> sanner at scripps.edu                        http://www.scripps.edu/sanner
> -----------------------------------------------------------------------
> 
> 
> -- 
> http://www.python.org/mailman/listinfo/python-list

---William Park, Open Geometry Consulting




More information about the Python-list mailing list