__repr__ affected after __getattr__ overloaded?

R

Roc Zhou

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:

#!/usr/bin/env python

class test:
def __init__(self):
self.x = 1
def __getattr__(self, attr_name):
try:
return self.__dict__[attr_name]
except KeyError:
self.__dict__[attr_name] = 'inexistent'
return self.__dict__[attr_name]

t = test()
print t.x
print t.y
print type(t)
T = t
print T.x
print t

So far, I still want the "print t" return "<test instance at ...>",
but when run, the result is:
sh$ python test.py
1
inexistent
<type 'instance'>
1
Traceback (most recent call last):
File "testtree.py", line 23, in ?
print t
TypeError: 'str' object is not callable

I also tried to overload __repr__, but no effect:
#!/usr/bin/env python

class test:
def __init__(self):
self.x = 1
def __getattr__(self, attr_name):
try:
return self.__dict__[attr_name]
except KeyError:
self.__dict__[attr_name] = 'inexistent'
return self.__dict__[attr_name]
def __repr__(self):
return 'test.__repr__'

t = test()
print t.x
print t.y
print type(t)
T = t
print T.x
print t

Still raise TypeError Exception:
Traceback (most recent call last):
File "testtree.py", line 23, in ?
print t
TypeError: 'str' object is not callable

So why?

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top