why __repr__ affected after __getattr__ overloaded?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Jun 22 03:08:39 EDT 2007


En Fri, 22 Jun 2007 03:43:26 -0300, Roc Zhou <chowroc.z at gmail.com>  
escribió:

> I'm sorry but I still have a question, look at this example:
>>>> class test:
> ...     def __init__(self):
> ...         self.x = 1
> ...     def __getattr__(self, attr_name):
> ...         print attr_name
> ...         if attr_name == 'y':
> ...             return 2
> ...         else:
> ...             raise AttributeError, attr_name
> ...
>>>> t = test()
>>>> t.x
> 1
>>>> t.y
> y
> 2
>>>> print t.x
> 1
>>>> print t
> __str__
> __repr__
> <__main__.test instance at 0xb7f6d6cc>
>
> Since __str__ and __repr__ does not exist because their names was
> printed, why not the "AttributeError" be raised?

This is the implementation of str() in action; tries to find a __str__  
method and fails; tries to find a __repr__ instead and fails; then uses  
the default representation.
See <http://docs.python.org/ref/customization.html#l2h-179>

-- 
Gabriel Genellina




More information about the Python-list mailing list