why __repr__ affected after __getattr__ overloaded?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Jun 22 08:58:32 CEST 2007


En Fri, 22 Jun 2007 02:48:50 -0300, Roc Zhou <chowroc.z at gmail.com>  
escribió:

> I know what's wrong. Thank you. And I think
> try:
>     return self.__dict__[attr_name]
> is unnecessary, because python will do it itself for us.

Exactly; by the time __getattr__ is called, you already know attr_name is  
not there.

> So now I have to overload __str__, but how can I make self.__str__
> print as builtin str(): at here, I want get the result like:
> <test instance at 0xb7bbb90c>
> ?

I would do the opposite: *only* create inexistent attributes when they are  
not "special". This way you don't mess with Python internals.

...   def __getattr__(self, name):
...     if name[:2]!='__' or name[-2:]!='__':
...       self.__dict__[name] = 'inexistent'
...       return self.__dict__[name]
...     raise AttributeError,name

This way you don't create "fake" attributes for things like __bases__ by  
example, and dir(), vars(), repr() etc. work as expected.

-- 
Gabriel Genellina




More information about the Python-list mailing list