Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model:<br>#!/usr/bin/env python<br><br>class test:<br> def __init__(self):<br>
self.x = 1<br> def __getattr__(self, attr_name):<br> try:<br> return self.__dict__[attr_name]<br> except KeyError:<br> self.__dict__[attr_name] = 'inexistent'<br> return self.__dict__[attr_name]
<br><br>t = test()<br>print t.x<br>print t.y<br>print type(t)<br>T = t<br>print T.x<br>print t<br><br>So far, I want the operation "print t" still return "<test instance at ...>", but the reuslt is:
<br>sh$ python test.py<br>1<br>inexistent<br><type 'instance'><br>1<br>Traceback (most recent call last):<br> File "testtree.py", line 23, in ?<br> print t<br>TypeError: 'str' object is not callable
<br><br>I also tried to overload __repr__ itself:<br><br>#!/usr/bin/env python<br><br>class test:<br> def __init__(self):<br> self.x = 1<br> def __getattr__(self, attr_name):<br> try:<br> return self.__dict__[attr_name]
<br> except KeyError:<br> self.__dict__[attr_name] = 'inexistent'<br> return self.__dict__[attr_name]<br> def __repr__(self):<br> return 'test.__repr__'<br><br>t = test()
<br>print t.x<br>print t.y<br>print type(t)<br>T = t<br>print T.x<br>print t<br><br>But the result remains:<br>Traceback (most recent call last):<br> File "testtree.py", line 23, in ?<br> print t<br>TypeError: 'str' object is not callable
<br><br>So why? What is the principles?<br><br>