__getattr__ and __cmp__
Remco Gerlich
scarblac at pino.selwerd.nl
Thu Oct 5 02:39:36 EDT 2000
Michel Sanner <sanner at scripps.edu> wrote in comp.lang.python:
> 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 ???
__getattr__ is only called for attributes that don't exist, and a1.value
exists. You can't make attributes invisible.
> >>> 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__
>
> I do not find the default object comparison any longer !
Because the __cmp__ method doesn't exist, getattr was called, and it pretends
that it does exist when it looks it up in __dict__.
> could anyone tell me what is happening ?
__getattr__ as you wrote it can't do anything useful (if val=="value" it
wouldn't get called, and if it is called, it can't look val up in __dict__).
I'm not sure what you're trying to do. If you're trying to hide value,
you can't do that. You can give a strong hint that value shouldn't be
touched from outside by calling it __value; the name of the class is
prepended to the variable if you want to access it:
>>> class A:
... def __init__(self, x):
... self.__value = x
...
>>> x = A(3)
>>> x.__value
Traceback (most recent call last):
Find "<stdin>", line 1, in ?
AttributeError: 'A' instance has no attribute '__value'
>>> x._A__value
3
--
Remco Gerlich
More information about the Python-list
mailing list